please why do i get an empty array when i do console.log(customers) but i get the right response which is status 200 when i do console.log(response.data);. i dont know if i am doing setCustomers(response.data.customers); in a wrong way. please help me
const [customers, setCustomers] = useState([]);
useEffect(() => {
const storedToken = JSON.parse(localStorage.getItem("token"))
const fetchCustomers = async () => {
const config = {
headers: { Authorization: `Bearer ${storedToken}` }
};
const response = await axios.get('https://exampleofalink.com/api/v1/customer', config);
console.log(response.data); // status 200
setCustomers(response.data.customers);
console.log(customers); //empty
};
fetchCustomers();
}, []);
i also tried
setCustomers(prevCustomers => [...prevCustomers, ...response.data.customers]);
but i still get an empty array
2
Answers
don’t try to console log when react is still settting the values, you will not see the change, but the values are there!
u can place another different useEffect to see the change like this:
When you setting a state, it doesn’t immediately change the value, it will changed on re-render, so you will see the previous value which is an empty array and can’t see the newest change immediately. There are two option if you want to see the values:
console.log
outside theuseEffect
console.log
into anotheruseEffect
that run whencustomers
value changedSee also: