1

How to execute the axios part and send the updated states props to Important component.

When I console.log I see that state passed as props with an empty object but after a fraction of seconds again states is updated with a new fetched value that means my return is running first then my usEffect axios part is running,

How can I make sure that axios part should run first then my return part. In first go updated part should be sent not the blank empty part

const initialState = {
    Important: [{}],
    Error: false
}

const reducer = (state, action) => {
    switch (action.type) {
        case "STEPFIRST":
            return {
                ...state,
                Important: action.payload,
            };
        case "STEPSecond":
            return {
                Error: true,
            };
        default:
            return state;
    }
}

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

    useEffect(() => {
        axios.get("https://example.com/")
            .then(response => {
                dispatch({
                    type: "STEPFIRST",
                    payload: response.data
                });
            })
            .catch(error => {
                dispatch({
                    type: "STEPSecond"
                });
            });
    },[]);

    const [xyz, xyzfn] = useState();
    console.log(xyz)

    return (
        <div>
        <Important states = {states} xyzfn={xyzfn} />
        <Foo xyz={xyz}/> 
        </div>
    );
};

export default Landing;

2 Answers 2

1

useEffect will always run after first rendering is done. You can have a loading state in your state and return the component accordingly.

const initialState = {
    Important: [{}],
    Error: false,
    isLoading: true
}

const reducer = (state, action) => {
    switch (action.type) {
        case "STEPFIRST":
            return {
                ...state,
                Important: action.payload,
                isLoading: false
            };
        case "STEPSecond":
            return {
                Error: true,
                isLoading: false
            };

        default:
            return state;
    }
}


const Landing = () => {
    const [states, dispatch] = useReducer(reducer, initialState)

    console.log(states)

    useEffect(() => {
        axios.get("https://example.com/")
            .then(response => {
                dispatch({
                    type: "STEPFIRST",
                    payload: response.data
                });
            })
            .catch(error => {
                dispatch({
                    type: "STEPSecond"
                });
            });
    },[]);

    const [xyz, xyzfn] = useState();
    console.log(xyz)

   if(state.isLoading){
       return <div>Loading....</div>
   }

    return (
        <div>
        <Important states = {states} xyzfn={xyzfn} />
        <Foo xyz={xyz}/> 
        </div>
    );
};
Sign up to request clarification or add additional context in comments.

Comments

0

useEffect callback runs after the render phase.

Also, fetch calls are asynchronous, so you want to use conditional rendering:

const Landing = () => {
  const [states, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    axios
      .get("https://example.com/")
      .then((response) => {
        dispatch({
          type: "STEPFIRST",
          payload: response.data,
        });
      })
      .catch((error) => {
        dispatch({
          type: "STEPSecond",
        });
      });
  }, []);

  // Use any comparison function to indicate that `states` changed.
  // like deep comparison function `isEqual` from lodash lib.
  return (
    <div>
      {!lodash.isEqual(states, initialState) && (
        <Important states={states} xyzfn={xyzfn} />
      )}
    </div>
  );
};

2 Comments

Hi @Dennis Vash I didn't understand this part !lodash.isEqual(states, initialState) . what exactly is lodash.isEqual?
See the comment in the answer, its a function from lodash library, you can google it. You need somehow to tell if states is equal to your initialState.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.