Reputation: 117
I'm trying to code a notification to appear when a fetch call has been successfully made to an API. I'm using redux with thunk to make fetch it and it changes the state of a prop called loading to true/false and an error prop to null/the error in string format. How could I accomplish this?
Upvotes: 0
Views: 424
Reputation: 46
You need to have an additional field which would inform the component that the fetch has ended. For example, in your dispatch(fetchSuccess(...))
which sets loading to false, you could add a message field in one of the reducers:
...
switch(action.type){
case FETCH_SUCCESS:
return {...state, data: action.payload, loading: false, message: 'success'}
...
}
It doesn't really matter what that is. If you API sends back a statusCode: 200
success response, you could use that as a message.
Another alternative is to create a selector and watch for a specific data: action.payload
change.
P.S.: If your notification handling is done through a separate redux reducer, you can do that as well:
...
try{
dispatch(fetchLoading())
...
const response = await axios.get(...)
const data = response.data
...
dispatch(fetchSuccess(data))
disaptch(openNotification())
} catch(error){
dispatch(fetchError(error.message))
}
...
Upvotes: 1