I am trying to call a function this.getUserFavorites()
inside a class method, inside of a .then()
after the fetch
but I always get this is not a function.
I've tried it without this
.
I've tried using bind in the constructor like:
this.getUserFavorites = this.getUserFavorites.bind(this);
export default class Dashboard extends Component {
constructor(){
super();
this.state = {
loggedIn: true,
name: '',
favorites: [],
modalVisible: false
}
}
addToFavorites(coinID){
const url = `${config.API_URL}/users/favorites`;
const authToken = TokenService.getAuthToken();
fetch(url,{
method: 'PATCH',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({ coinID })
})
.then( response => {
if(response.ok){
// THIS ISNT WORKING
this.getUserFavorites();
}
})
}
getUserFavorites = () => {
const userID = TokenService.getAuthUserID();
const url = `${config.API_URL}/users/${userID}/favorites`;
fetch(url)
.then( response => {
return response.ok
? response.json()
: alert(response.statusText)
})
.then( data => {
if(data.favorites !== null){
this.setState({
favorites: data.favorites
})
}
})
}
}