Parth Tiwari
Parth Tiwari

Reputation: 486

How to Update state using axios in React?

How can I run my useEffect at top priority so that my state can be updated first then further processing can be done

I want my axios part should run first inside useEffect so that my state can be update first and then further I can use that.

Here is error: TypeError: Cannot read property 'id' of undefined when I console it shows states is not updated it holds empty array

Here is mine code:

const initialState = {
    staff: [],
    isFetching: false,
    hasError: false
}

const Staff = ({ setStaffid }) => {
    const [states, dispatch] = useReducer(reducer, initialState)
    console.log(states)

    useEffect(() => {
        dispatch({
        axios.get("https://example.com/staff")
            .then(response => {
                console.log(response)
                console.log(response.data)
                dispatch({
                    type: "FETCHSUCCESS",
                    payload: response.data.access
                });
            })
            .catch(error => {
                console.log(error);
                dispatch({
                    type: "FETCHFAILURE"
                });
            });
    }, );

    useEffect(() => {
        const id = states.staff[0].id;
        setStaffid(id);
    }, []);

    return (
        <div>

        </div>
    );
};

export default Staff;


Upvotes: 0

Views: 44

Answers (1)

Sandy
Sandy

Reputation: 11687

Error is because you are trying to access property 'id' on an undefined object.

Change useEffect

useEffect(() => {
  const staff = states.staff[0];
  if(staff) setStaffid(staff.id);
}, [states.staff]);

To get rid of error just change your initialState.

const initialState = {
    staff: [{}],
    isFetching: false,
    hasError: false
}

Hope it helps.

Upvotes: 1

Related Questions