How to add a random number in the following URL in reactjs?

Viewed 246

I have a project, where I have a create/delete/update.

so in the update component, I have to update the post Title, post Text, and image. so when I update them and press the submit button to save the changes, it works well but it doesn't display the changed image on the UI, till I reload the page, but it does change the image in the file system,

so the URL is like this: http://localhost:3000/Post-Review/307 i want to add a random number for this URL, after the ID

or if there is any other way to solve this problem.

here is the router: <Route path="/Post-Review/:id" exact> <Post /> </Route>

Here is my submitting code:

    const submitUpdate = (e) => {
    e.preventDefault();
    const formData = postToFormData(
      postObject,
      file,
      selectedTags,
      deletedTags
    );
    formData.append("id", actualId);

    axios
      .put(`${targetServer}/posts/byId/${actualId}`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          accessToken: localStorage.getItem("accessToken"),
        },
      })
      .then((res) => {
        if (res.data.error) {
          alert(res.data.error);
        } else {
          history.push("/");
        }
      });
  };

thanks

2 Answers

Couldn't you just use a useEffect inside the component and put the random number in the image ref?

src="myimage.jpg?timestamp=123"

the random number could be the timestamp. This way you would be sure that it will always be a unique value.

const timestamp = new Date().getTime()

#Update

Here is the image URL, that is what I am using now.

 src={`${targetServer}/posts/image/${postObject.id}`}

if u want to update the UI, you can simply re-fetch the data after the POST request succeeds. React is built for this kind of use.

here is a sample code :

// your post data goes here
const [data, setData] = useState({

...
})
// a method to fetch post data by id
const fetch_data = (post_id) => {
axios
  .get(`${targetServer}/posts/byId/${actualId}`, {
    headers: {
      "Content-Type": "multipart/form-data",
      accessToken: localStorage.getItem("accessToken"),
    },
  }).then((res) => {
    if (res.data.error) {
      alert(res.data.error);
    } else {
      // if the update done, then call fetch
      setData(res.data)
    }
  });

}
// the actual update function
const submitUpdate = (e) => {
 e.preventDefault();
 const formData = postToFormData(
  postObject,
  file,
  selectedTags,
  deletedTags
 );
 formData.append("id", actualId);

 axios
  .put(`${targetServer}/posts/byId/${actualId}`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
      accessToken: localStorage.getItem("accessToken"),
    },
  })
  .then((res) => {
    if (res.data.error) {
      alert(res.data.error);
    } else {
      // if the update done, then call fetch
      fetch_data(post_id)
    }
  });
}
Related