2

I must have this setup incorrectly because it is not working. If I put a console.log in my if statement it shows up, so I know it is getting to that point, but it is not redirecting. Am I doing this wrong...

...

checkUserAuth = () => {
return fetch(process.env.REACT_APP_API_URL + '/authCheck', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': window.localStorage.getItem('token')
  },
  body: JSON.stringify({
    itemid: this.props.itemid
  })
})
}

render(){

this.checkUserAuth().then(response => response.json()).then(data => {
  if(data === 'false') {
    return <Redirect to='/' />
  }
}).catch(err => console.log(err))

....
JamieTom
  • 101
  • 2
  • 14
  • I'm realizing now this kind of authorization can probably be handled easier on the server side, but I still would like to know what I am doing wrong so I can better understand how this works. – JamieTom Mar 08 '19 at 20:15

1 Answers1

1

For side-effects use cases, use componentDidMount() and then update internal state that will trigger render method:

checkUserAuth = () => {
  return fetch(process.env.REACT_APP_API_URL + '/authCheck', {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': window.localStorage.getItem('token')
    },
    body: JSON.stringify({
      itemid: this.props.itemid
    })
  })
}

componentDidMount() {
  this.checkUserAuth().then(response => response.json()).then(data => {
    this.setState({data});
  });
}

render() {
  if(data === 'false') {
      return <Redirect to='/' />
  } else {
    ... do something else
  }
}
zooblin
  • 2,172
  • 2
  • 27
  • 33
  • Interesting. This worked, but is it advised not to do something like I am trying to do, or is it an okay practice? – JamieTom Mar 08 '19 at 20:28
  • 1
    Well since your component based on data that comes asynchronously from server there is no another approach, it will be much better if during fetch process user will experience any kind of loader or progress bar, but in general this is approach. – zooblin Mar 08 '19 at 20:31