H
H
Hlib2019-08-27 13:50:43
React
Hlib, 2019-08-27 13:50:43

How to 'optimize' how fetch works with redux?

Hello, the situation is this:
When working with the API (via fetch), I upload files to the state of the redax.
The problem is that when I try to register some variables via connect and use them in the code, the API does not have time to load and it turns out that the state in the editor is empty
Accordingly, this causes errors like Cannot read property 'something' of undefined
Is there any other way to work besides (if props.wrap.something !== undefined)?
I store the request to the server in separate actions
+ how to track if the request passed?
For example:

const [isLoading, setIsLoading] = useState(true);

  useEffect(()=>{
    let lat;
    let long;
    let proxy = 'https://cors-anywhere.herokuapp.com/';
    navigator.geolocation.getCurrentPosition(position =>{
      lat = position.coords.latitude;
      long = position.coords.longitude;
      props.onGetWeather(`${proxy}https://api.darksky.net/forecast/8f2f993672f627f5cc108000ff1f78bd/${lat},${long}`)
      setIsLoading(false);
    });
  }, [])

export default connect(
  state =>({
    weather: state.weather,
  }),
  dispatch =>({
    onGetWeather: (url) =>{
      dispatch(getWeather(url))
    }
  })
)(Weather)

export function getWeatherSuccess(data){
  return{
    type: 'FETCH_WEATHER_DATA',
    data
  }
}

export function getWeather(url){
  return (dispatch)=>{
    fetch(url, {method: 'GET'})
      .then(response =>{
        if(!response.ok){
          console.log('Error');
        }
          return response
      })
      .then(response => response.json())
      .then(data => dispatch(getWeatherSuccess(data)))
  }
}

How to track props.onGetWeather passed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-27
@Mysianio

Add load state and errors to the reducer:

initialState = {
  isFetching: false,
  data: null,
  error: null,
};

In the component:
const Example = ({ isFetching, error, data }) => {
  if (isFetching) return <Preloader />;
  if (error) return <Error error={error} />;
  if (!data) return null; // или что хотите показывать при отсутствии данных
  
  // далее обращения к ключам data и JSX.
}

You don't need to use local load state.
Change the method onGetWeather(path)togetWeather(lat, long)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question