I’m trying to get data from the backend API and map it to the table but no data is appearing. If I console data I can see the data I need in an array. I would appreciate any help, I’m new to React pardon me. Cheers……………………………………………………………..
import { getAllCustomers } from "../../../../features/customers/customerSlice";
const [data, setData] = useState();
const fetchInfo = () => {
dispatch(getAllCustomers());
};
useEffect(() => {
fetchInfo();
}, [setData]);
console.log(data);
const columns = [
{ title: "ID", field: "id" },
{ title: "Username", field: "username" },
{ title: "Name", field: "name" },
{ title: "Email", field: "email" },
{ title: "Phone", field: "phone" },
{ title: "Web Link", field: 'website' }
]
return (
<CardBody>
<ThemeProvider theme={defaultMaterialTheme}>
<MaterialTable
title="Employee Data"
data={data}
columns={columns}
/>
</ThemeProvider>
</CardBody>
);
};
export default Customers;
customerSlice.jsx
const initialState = {
customer: [],
autoCustomer: [],
customers: [],
isLoading: false,
isError: false,
isSuccess: false,
message: "",
};
// Get all customers
export const getAllCustomers = createAsyncThunk(
"customer/getAllCustomers",
async (_, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token;
return await customerService.getAllCustomers(token);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
customerService.jsx
const getAllCustomers = async (token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
};
const response = await axios.get(
"http://localhost:8000/api/v1/customer/paginate-customer",
config
);
return response.data;
};
I’d appreciate any tips. 🙂
2
Answers
in your code, setData is never called, so data state is always [] (the init value you gave it)
If getAllCustomers returns an array of customers, maybe this should be more appropriate:
Also, your use of useEffect is uneffective, setData should not be in the dependancies array since it will not change. More information on hooks here: https://fr.reactjs.org/docs/hooks-intro.html
remove dependencies that you mention inside useEffect and that depedencies is is function remove [] empty can work