Reputation: 17
i try to post the values to the mongo server and get the values from server with same route.it is working but each and every time i need to reload the page manualy. is it right to do the POST and GET request in same route.
i try to make single page application
const createJob = async () => {
dispatch({ type: CREATE_LIST_BEGIN })
try {
const { item, price, stock } = state
await axios.post('/api/v1/list', { item, price, stock })
dispatch({ type: CREATE_LIST_SUCCESS })
dispatch({ type: CLEAR_VALUES })
} catch (error) {
if (error.response.status === 401) return
dispatch({ type: CREATE_LIST_ERROR, payload: { msg: error.response.data.msg } })
}
clearAlert()
}
const getItems = async () => {
dispatch({ type: GET_LIST_BEGIN })
try {
const { data } = await axios.get('/api/v1/list')
const { items } = data
dispatch({ type: GET_LIST_SUCCESS, payload: { items } })
} catch (error) {
console.log(error.response)
}
}
useEffect(() => {
getItems()
}, [])
Upvotes: 0
Views: 779
Reputation: 4913
The POST
handler in your API should return the newly added record and createJob()
should add the record to your store. So it would look something like this:
const createJob = async () => {
dispatch({ type: CREATE_LIST_BEGIN })
try {
const { item, price, stock } = state
// get the new item returned from API
const {data} = await axios.post('/api/v1/list', { item, price, stock })
// dispatch an action creator which adds the new item
dispatch({ type: ADD_LIST_ITEM, payload: { item: data.item } })
dispatch({ type: CREATE_LIST_SUCCESS })
dispatch({ type: CLEAR_VALUES })
} catch (error) {
if (error.response.status === 401) return
dispatch({ type: CREATE_LIST_ERROR, payload: { msg: error.response.data.msg } })
}
clearAlert()
}
Upvotes: 1