I am trying to fetch data from my database and then using useReducer if the fetch is successful I then want to return it as state so I can pass it down to components.
I have console.log'd req.data and it is fetching the correct data however it isn't saving to state when I return the value in the reducer.
The state is supposed to be an array of objects.
Can anyone see where I'm going wrong here?
import React, { createContext, useReducer, useEffect } from 'react'
import axios from 'axios'
export const OrganisationsContext = createContext()
export const OrganisationsContextProvider = ( { children }) => {
const initState = []
const organisationsReducer = (state, action) => {
console.log(state)
switch(action.type) {
case 'FETCH_SUCCESS':
return [...state, action.payload]
case 'FETCH_ERROR':
throw new Error(action.payload)
default:
return state
}
}
useEffect(() => {
const initFetch = async () => {
try {
const req = await axios.get('/api/fetch_organisations')
organisationsDispatch({action: 'FETCH_SUCCESS', payload: req.data})
} catch (err) {
organisationsDispatch({action: 'FETCH_ERROR', payload: err})
}
}
initFetch()
}, [])
const [organisations, organisationsDispatch] = useReducer(organisationsReducer, initState)
return (
<OrganisationsContext.Provider value={{organisations, organisationsDispatch}}>
{children}
</OrganisationsContext.Provider>
)
}