skip to Main Content

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


  1. 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:

    useEffect(() => {
    
      console.log(customers);
      
      }, [customers]);
    
    Login or Signup to reply.
  2. 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:

    1. Put console.log outside the useEffect
    2. Or, add console.log into another useEffect that run when customers value changed
      useEffect(() => {console.log(customers)}, [customers])
      

    See also:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search