1
votes

In my app I'm using React Router to add routes to my app. I'm redirecting to my home(feed) page from my AddAlbum class component using withRouter history once a user clicks save. My problem is my AddAlbum component is updating my home page so I need to re-load my home page once I redirect to see the changes made from my AddAlbum component. How would I accomplish this?

Here is what my routes look like in my App.js Component:

import { BrowserRouter, Router, Route } from "react-router-dom";
return (
    <BrowserRouter>
      <div className="App">
      <Router history={history}>
      <Route path="/album/create" component={AddAlbum}/>
      <Route exact path="/feed" component={Feed}/>
      </Router>
      </div>
    </BrowserRouter>
  );

Both AddAlbum and home(Feed) are class components.

In my AddAlbum component I'm using withRouter and history in an onClick method to redirect. Here's the full function with the button (Redirect on the last .then():)

this.onClick = this.onClick.bind(this);
this.save2 = this.save2.bind(this);

save2(event) {
  event.preventDefault();
  let user_id;
  let image;
  let data;
  const { history } = this.props;

  Promise.resolve().then(()=>{
      user_id = this.context.user.sub;
      image = this.state.file;
      data = new FormData()
      data.append('file', this.state.file)
  }).then(()=> { 
      this.setState(prevState => ({
      files: prevState.files.map((file, index) => ({...file, index})
  )}));

  let files = this.state.files;
   this.setState(prevState => ({
   albums: {...prevState.albums, files, user_id}
}))

   Array.from(this.state.songsList).forEach(song => {
    data.append('songs', song)
  })

  data.append('albums', JSON.stringify(this.state.albums))


}).then(()=> {
    axios.post("http://localhost:3000/albums", data, { 
  }).then(res => { // then print response status
    console.log(res.statusText)
 })
})
.then(()=> {
  const { match, location, history } = this.props;
  history.push('/feed');
})
.catch((err)=> {console.log(err)});

}

onClick(event) {
  let albums = this.state.albums;
  if(albums.date  === "" || albums.title  === "" || albums.description === "") {
    alert("ERROR: Fields Must Be Filled In Before You Save");
    } else {
  this.save2(event);
  }
}

render() {
    return(
        <ButtonToggle onClick={this.onClick} color="success">
            Save
        </ButtonToggle> 
    )
}

How would I re-load my home(Feed) component once I redirect to it?

2
Are you using some sort of global state? because on every route change your component should render again. without any old values. - jean182
@JeanAguilar What do you mean by global state and where? If I click on links with React Router I don't think it's supposed to re-load. Idk about if I redirect using withRouter though. - DDavis25
The redirect works fine, right? - Nico Diz
Yes, the redirect works fine - DDavis25
Please, add more code of the AddAlbum component. Specially the Save button section. - Nico Diz

2 Answers

0
votes

PROBLEM: after your axios.post (9 lines before the catch), you do not update your state. That is why you do not see the changes.

SOLUTION 1: if the POST request returns correctly, update your state (adding the album to your album’s array).

SOLUTION 2: if the POST request returns correctly, reload your page with window.location.reload(), so you will get your albums updated from apicall. Something like this:

    axios.post(yourURL, yourData)
        .then(res => {
            // check if response is correct and
            window.location.reload();
        })
        .catch(console.error);

Hope it helps.

0
votes

I just did a quick scan on your code but I think the problem is in your axios post request. This way, when you redirect to /feed it'll pull the updated data from that endpoint.

axios.post("http://localhost:3000/albums", data, {})
  .then(res => {
      // then print response status
      console.log(res.statusText);

      // redirect only when your http request is complete.
      history.push("/feed");
  });