Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

reactjs - Updating React state after updating Mongo DB via Express endpoint

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...