Eber Leguizamón
Eber Leguizamón

Reputation: 11

trigger function after promise resolve

I want to execute a function after a post request. This function update my state automatically with the new movements created.

My service:

export const getMovements = async () => {
  try {
    const res = await axios.get('http://localhost:4001/movements')
    const { data } = res
    return data
  } catch (err) {
    return console.log(err)
  }
}

Then i call get movements in my other component and set my state, works so far:

useEffect(() => {
    if (user) {
      getMovements().then((data) => {
        setMovements(data)
      })
    }
  }, [user])

The problem is when i make a post request: the promise resolves and i get the response, {message:' Movement created successfully' }, but getMovements() is not executed, and i need it to refresh my page. If i refresh my page manually yeah it work, but i want to trigger the function(getMovements) automatically after resolve the promise.

const addMovement = ({ description, category, amount, type }) => {
    axios
      .post('http://localhost:4001/movements/create', {
        description,
        category,
        amount,
        type,
        date: fullDate
      })
      .then((res) => {
        console.log(res)
        getMovements()
      })
      .catch((err) => console.log(err))
  }

It works if i do like this (but i want separated logic):

 useEffect(() => {
        if (user) {
          getMovements()
        }
      }, [user])
    

      const getMovements = async () => {
        try {
          const { data } = await axios.get('http://localhost:4001/movements')
          setMovements(data)
        } catch (err) {
          console.log(err)
        }


 const addMovement = ({ description, category, amount, type }) => {
    axios
      .post('http://localhost:4001/movements/create', {
        description,
        category,
        amount,
        type,
        date: fullDate
      })
      .then((res) => {
        console.log(res)
        getMovements()
      })
      .catch((err) => console.log(err))
  }

kisses

Upvotes: 0

Views: 496

Answers (1)

Pratik Wadekar
Pratik Wadekar

Reputation: 1274

You could convert your addMovement method to be async and await getMovements()

const addMovement = async ({ description, category, amount, type }) => {
  try {
    const response = await axios.post(
      "http://localhost:4001/movements/create",
      {
        description,
        category,
        amount,
        type,
        date: fullDate
      }
    );
    console.log(response);
    await getMovements();
  } catch (err) {
    console.log(err);
  }
};

Upvotes: 1

Related Questions