0

I am using useReducer inside of context which makes API calls to mongoDB to make changes to the database.

When creating a new document in the collection organisation I then send back an object with the new organisation that was just created. What I'm trying to get it to do is to update the context with the new organisation after it has been successfully created so that React re-renders and the user can see the most up-to-date information.

I am successfuly creating a new organisation however they don't display until I refresh the app.

Can anyone see where I'm going wrong so that I can have React re-render with the new organisation once it has been made?

Back end

app.post('/api/organisations', requireLogin, async (req, res) => {
    try {
        const { organisationName, organisationUsers } = req.body
        const parsedUsers = organisationUsers.split(',').filter(el => el.length > 0).map(el => el.replace(/ /g, '')).concat([req.user.email])
        const organisation = await new Organisation({
            organisationName,
            organisationUsers: parsedUsers,
            organisationOwner: req.user.email
        }).save()
        res.send(organisation)
    } catch (err) {
        console.log(err)
        res.status(400)
        res.send({ error: err })
        return
    }
})

Front end (context)

const initState = []

const organisationsReducer = (state, action) => {
    const updatedState = state.filter(org => org._id !== action.payload._id)
    switch (action.type) {
        case 'CREATE_SUCCESS':
            return [...state, ...action.payload]
        case 'CREATE_ERROR':
            console.error(action.payload)
        case 'FETCH_SUCCESS':
            return [...state, ...action.payload]
        case 'FETCH_ERROR':
            return [...state]
        case 'UPDATE_SUCCESS':
            return [...updatedState, action.payload]
        case 'UPDATE_ERROR':
            console.error(action.payload)
            return [...state]
        case 'DELETE_SUCCESS':
            return [...updatedState]
        case 'DELETE_ERROR':
            console.error(action.payload)
            return [...state]
        default:
            return state
    }

const createOrganisation = async (formData) => {
        try {
            const req = await axios.post('/api/organisations', formData)
            organisationsDispatch({action: 'CREATE_SUCCESS', payload: req.data})
        } catch (err) {
            organisationsDispatch({action: 'CREATE_ERROR', payload: err})
        }
}
const [organisations, organisationsDispatch] = useReducer(organisationsReducer, initState)

return (
    <OrganisationsContext.Provider value={{ organisations, updateOrganisation, editOrganisationUser, createOrganisation, deleteOrganisation }}>
        {children}
    </OrganisationsContext.Provider>
)

1 Answers1

0

I figured the issue out - in the dispatch function I was using action instead of type