Effective way if updating SQL Data Retrieved in ReactJS

Viewed 27

Good morning, stackoverflow!

In light of learning ReactJS in my free time between school and work, I've been trying to figure out an effective way to refresh SQL data retrieved once a new result has been submitted. I created a custom review system for my mechanic themed website, once the user submits a new review, it sends it to the SQL system. However, I'm trying to find an effective way to refresh the results on the page once the submit button is hit. I tried running several dependencies in the useEffect hook, I can't find an effective way.

I'm running MySQL, Express, Axios, CORS, and BodyParser

  const [reviewList, setReviewList] = useState([])

  const [submitDiv, setSubmitDiv] = useState(false)

  const toggleSubmit = () => {
    setSubmitDiv(!submitDiv)
  }

  const submitReview = (e) => {
    e.preventDefault()
    e.target.reset()
    Axios.post("http://localhost:3001/submit", {
      username: username,
      email: email,
      reviewtext: reviewtext
    })
    toggleSubmit()
  }

  useEffect(() => {
    Axios.get('http://localhost:3001/getReviews').then((response) => {
      setReviewList(response.data)
      console.log("Review list grabbed.")
    })
  }, [])

Any help would be greatly appreciated!

Any documentation would be appreciated as well.

1 Answers

Currently, the only time you load from the database is when the component mounts. If you can reliably predict what will happen when you POST to http://localhost:3001/submit, then you can update your state locally without fetching from the database again. For example:

const submitReview = (e) => {
  e.preventDefault()
  e.target.reset()
  const newReview = {
    username: username,
    email: email,
    reviewtext: reviewtext
  }
  Axios.post("http://localhost:3001/submit", newReview)
  setReviewList(prev => [...prev, newReview]); // <--- Updating state
  toggleSubmit()
}

If you instead want to get from the database to make sure you have accurate data, you can do another axios.get:

const submitReview = (e) => {
  e.preventDefault()
  e.target.reset()
  Axios.post("http://localhost:3001/submit", {
    username: username,
    email: email,
    reviewtext: reviewtext
  }).then(() => {
    return Axios.get('http://localhost:3001/getReviews')
  }).then(() => {
    setReviewList(response.data)
  });
  toggleSubmit()
}

Or the same thing using async/await:

const submitReview = async (e) => {
  e.preventDefault()
  e.target.reset()
  toggleSubmit()
  await Axios.post("http://localhost:3001/submit", {
    username: username,
    email: email,
    reviewtext: reviewtext
  })
  const response = await Axios.get('http://localhost:3001/getReviews')
  setReviewList(response.data)
}
Related