How to take an action after react-context function ends it's execution inside a component

Viewed 18

I tried to do some searches and I found Wait for a Function to Finish in JavaScript, but i'm struggling with the search itself and how to use it.

My use-case:

I've a function that populates a context in react, and this function is async function to work correctly with the API. After successful execution a specific state in the context is populated.

I use this function inside a onClick for a button.

What I want to achieve:

I want to take a decision inside the onClick depending on the output of the context function.

ex:

let's assume that I've a function in context returns an object of to-do

    const [state, setState] = useState({
    error: null,
    isTodoLoading: false,
    todo: {},
    });

    const getSpecificTodo = async (projectID) => {
    setState(ps => ({
        ...ps,
        todo: {},
        error: null,
        isTodoLoading: true,
    }));

    await API.getTodo(projectID)
        .then(res => {
            setState(ps => ({
                ...ps,
                todo: res.data,
                error: null,
                isTodoLoading: false,
            }));
        })
        .catch(e => {
            setState(ps => ({
                ...ps,
                todo: {},
                error: formatError(e, `Failed To Retrieve Project Consent!`),
                isTodoLoading: false,
            }));
        })
}

I'm using this context function inside onClick of a button to display a Modal with the todo

  const handleOnClick = (projectId) => {
   getSpecificTodo(projectId)
//Here I want to wait till the getSpecificToDo finishes its work and then act upon it
//I want to see if there is no todo returned after this successful return then i'll redirect user
//to another page, but if there's todo i'll display a modal with the data returned
      }

I hope that I explained what I want to do clearly.

I'm using:

  • React JS
  • Context API
  • Antd
0 Answers
Related