简体   繁体   中英

insert response from axios.post into state

I use axios to connect to my api and get a bunch of graphic files for ships. Like this:

axios.get(`/api/serveEnemyShips/graphics-files/${shipId}/files`)
  .then((response) => {
    this.setState({ files: response.data })
  })

This works and sets the state for files.

What would be the best way of adding to this state if a user wanted to upload a custom graphic?

I initially just used axios.post to upload the ship graphic, then performed another axios.get against my api, but that seems expensive.

I was hoping I could just upload the graphic, and then insert that response data(from the axios post) into my state and not have to do another axios.get after the upload.

Thanks!

Your last paragraph sounds reasonable. Granted that you get the newly created graphic in response to the post request, you could just add it to your array in state. If you don't get the data in the response, you most likely have all the data locally already, which you can use.

Example

axios.post(`/api/serveEnemyShips/graphics-files/${shipId}/files`, newFile)
  .then((response) => {
    this.setState(previousState => {
      return { files: [...previousState.files, response.data] };
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM