0

I'm facing a weird issue when trying to change a value of the state object after performing a GET request with either fetch or axios (not working with both). My code is pretty basic and I tried a lot of solutions that I found online but none of them is working.

This is the code I have so far ...

class FilterScreen extends React.Component {

    state = {
        selectedCity: null,
        cities: [],
        selectedSpecialty: null,
        specialties: [],
    };


    componentWillMount() {
        this.fetchCities();
    }

    fetchCities = () => {

        fetch(`http://127.0.0.1:8000/app/cities`)
            .then(res => res.json())
            .then(e => {
                this.setState({
                    results: e.data.map(item => ({
                        label: item.name,
                        value: item.id
                    }))
                });
            })
            .catch(
                () => (
                    alert('There was an issue while fetching the doctors.')
                )
                );
        };

    render() {
        return (
          ... the body of the component...
            )}
}

export default FilterScreen;

I really can't understand what I'm doing wrong here. I'm pretty new to React Native and maybe this has something to do with the lifecycles but I'm sure that componentWillMount is the right way to do it. Maybe I'm wrong ... Any kinda help is appreciated :D

Maro Paro
  • 111
  • 1
  • 2
  • 12
  • Did you debug it and check that setState is actually called? The question lacks https://stackoverflow.com/help/mcve . Whatever the problem is, you should try to replicate it with regular React - Stackblitz, etc. This way React Native could be ruled out from the equation. As it was mentioned, componentDidMount has to be used, but it's unlikely this is the only problem here. – Estus Flask Jul 30 '18 at 12:36
  • @estus I debugged it by logging in the console right after the setState is being called and there the state is set ok. But outside of the fetch or axios request when i try to log the new state... it's still the same as the beginning as if it is being reset to the old state. I also tried using componentDidMount – Maro Paro Jul 30 '18 at 12:43

1 Answers1

1

You should make async calls in componentDidMount. Please see this.

Efe
  • 5,180
  • 2
  • 21
  • 33
  • 1
    I tired it this way: `code componentDidMount() { axios.get(`http://127.0.0.1:8000/app/cities`) .then(response => { if (response.data.error === false) { this.setState({ cities: response.data.data.map(item => ({ label: item.name, value: item.id })) }); console.log(this.state.cities); } }); console.log(this.state.cities); } ` – Maro Paro Jul 30 '18 at 12:32
  • You would still use fetch instead of axios. – Efe Jul 30 '18 at 12:34
  • @MaroParo i think this is what you need to know [**setState behaviour**](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately/42593250#42593250), here you are getting confused :) – Mayank Shukla Jul 30 '18 at 12:34
  • @Efe I did it with axios as it was described in the link you provided. I switched do t fetch and still not working. Right after the state is set (the first console log shows everything ok). Right after the fetch (second console log) the array is again empty. – Maro Paro Jul 30 '18 at 12:40
  • 1
    @MayankShukla the console log on the callback function shows the state value as changed – Maro Paro Jul 30 '18 at 12:52
  • 1
    Apparently the state was being edit after all but my debugging logic was wrong. – Maro Paro Jul 30 '18 at 13:13