H
H
Hlib2019-08-28 20:54:06
React
Hlib, 2019-08-28 20:54:06

Why is the component not updating after accepting props from redux?

Hello, there was such a problem
Functional component:

import React, {useEffect, useState} from 'react';
import {connect} from 'react-redux';
import {getWeather} from '../actions/getWeather.js';

const Weather = (props) =>{

  const [isFetching, setFetching] = useState(true);

  useEffect(()=>{
    let lat;
    let long;
    navigator.geolocation.getCurrentPosition(position =>{
      lat = position.coords.latitude+17;
      long = position.coords.longitude;
      props.onGetWeather(lat,long)
    });
    setFetching(props.weather.isFetching)
  },[])

  if(isFetching){
    return(
      <div id='loading'>
        <h1>Loading... {props.weather.error}</h1>
      </div>
    )
  }else{
      return(
        <React.Fragment>
            <React.Fragment>
              <h1>{props.weather.data.timezone}</h1>
              <div className='weatherWrap'>
              <h3>{props.weather.data.currently.temperature}</h3>
              <h5>{props.weather.data.currently.summary}</h5>
              </div>
            </React.Fragment>
        </React.Fragment>
      )
  }
}

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

The fact is that when onGetWeather fetches the data and they come to the editor (1-2 seconds), the component simply does not update, no matter what I do.
Data comes to redux:
{
    isFetching: false,
    data: (данные с сервера)
}

The component is updated and everything works as it should only if I update it natively (I will put a button that updates the state, for example)
What is the problem? How to fix it?
I've tried everything and I'm going a little crazy.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
suberg, 2019-08-28
@Mysianio

UseEffect should work for you when changing props, that is, you need to specify it in the props array

useEffect(()=>{
   ...
},[props])

Install the eslint -plugin-react-hooks plugin, it helps to catch such shortcomings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question