javascriptreactjsmobxmobx-reactmobx-react-lite

How correctly fetch data by id using React mobx lite?


I wrote some code with MOBX! Now I have an input field and I take that value and send that string to API and fetching data! afterward, I get data from the store but it doesn't refreshing when I write new city in input! I want to add city in input and display weather data immediately!!!!

here is my code on CodeSandbox:

https://codesandbox.io/s/practical-wood-p13yd?file=/src/Components/NewNoteInput.tsx


Solution

  • You need to add makeObservable call inside your store constructor:

      constructor() {
        // this.weather = '';
        this.weathers = [];
        this.fetchingData = false;
    
        makeObservable(this);
      }
    

    See this answer for more details: mobx-react observer don't fires when I set observable

    Also, change API link to https: const BASEURL = "https://api.openweathermap.org";

    Also, assigning API response to weathers does not make sense, because your weathers property is an array. You need to push object to it, like that:

        runInAction(() => {
          // That way every new weather response will be added to your array
          this.weathers.push(weather);
          this.fetchingData = false;
        });