I have a React frontend that lists some activities, grouped by date into events. The user can click a button on these items to sign themselves up to these activities. On click of the button, an axios
PUT request is made to an Express API that updates the record in a Mongo DB database of that task. I'm using a Redux-esque implementation of the Context API to manage the state for this. The call looks like so:
function updateActivity(activityId, activityData) {
const body = {
activityId,
activityData,
};
dispatch({ type: UPDATE_ACTIVITY_ASYNC });
axios.put(`${process.env.REACT_APP_API_URL}/activities`, body, { headers: { 'Content-Type': 'application/json' } })
.then(() => dispatch({ type: UPDATE_ACTIVITY_SUCCESS }))
.then(() => getEvents())
.catch((err) => dispatch({ type: UPDATE_ACTIVITY_ERROR, err }));
}
Once the call has been successful, there is another GET call made to retrieve the whole list of events (getEvents()
) which in turn updates the state of the app. I'm left wondering if this is the best way to go about this - to make another call to get all the events again seems a little inefficient. The PUT response returns the updated activity, but currently has no knowledge of which event it was a part.
Currently the activity
and event
models are separate in the API and DB - would it be better to properly include the activities in the event model (as opposed to a reference, which is what they are at the moment), and just update the one event in state? An event model is structured like so:
// Model for dates where activities are happening
const eventSchema = new Schema({
date: {
type: Date,
required: true
},
name: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
// Insert array of refs of activities here
activities: [{ type: Schema.Types.ObjectId, ref: 'Activity' }],
});
question from:
https://stackoverflow.com/questions/65865237/updating-react-state-after-updating-mongo-db-via-express-endpoint 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…