0

i set the users state with axios data but in useEffect hook whereevery i console.log(users) its show the default state that is [] array. please see the comment for better undarstand.

let [users, setUsers] = useState([]);

useEffect(() => {
    axios.get('/chat_user_list').then((res) => {
        setUsers(res.data);
    });
    
    let pusher = new Pusher('api-key-over-here', {
        cluster: 'ap1',
        authEndpoint: "/admin/broadcasting/auth",
        auth: {
            headers: {
                "X-CSRF-Token": csrfToken,
                "Accept": "application/json"
            },
        },
    });
    let channel = pusher.subscribe(`presence-room`);

    channel.bind("pusher:member_added", (member) => {
        //how can i get the updated users state value over here
        console.log(users); //set the users with axios data but it still return the default state; that is an [] array

    });

}, []);

kundefine
  • 83
  • 10

1 Answers1

0

Your axios call is asynchronous, so it's still being completed while the rest of the code in your useEffect continues to run. If you put the rest of your logic inside your then you will have access to res.data which is what users will be set to. Note - since setUsers is async also, users itself may not be updated when you get to your pusher functionality.

useEffect(() => {
   axios.get('/chat_user_list').then((res) => {
        setUsers(res.data);
let pusher = new Pusher('api-key-over-here', {
        cluster: 'ap1',
        authEndpoint: "/admin/broadcasting/auth",
        auth: {
            headers: {
                "X-CSRF-Token": csrfToken,
                "Accept": "application/json"
            },
        },
    });
    let channel = pusher.subscribe(`presence-room`);

    channel.bind("pusher:member_added", (member) => {
        console.log(res.data); 
        // you should have access to updated users here
    });
}, []);
larz
  • 5,724
  • 2
  • 11
  • 20