0

I'M trying to use Weather API with React Native, but the error below occurred. It seems that a problem is that const is used before getAdressData done. How can I use const in this case and fix this error?

Error

undefined is not an object (evaluating 'whether.sys.sunrise')

Codes


〜〜〜〜〜〜〜〜〜〜
export const AddressScreen = () => {
    const [address, setAddress] = useState('');

    const baseURL = `${APIKey}`
    
    const getAddressData = () => {
        axios.get(baseURL)
                .then((response) => {setAddress(response.data)})
                .catch(error => console.log(error))
        };
    
    const sunrise =  new Date(weather.sys.sunrise * 1000); //Error
    const sunriseTime = sunrise.toLocaleTimeString();

    return (
        <KeyboardAvoidingView>
            〜〜〜〜〜〜〜〜
            <View>
                <Text>
                       Sunrise: {(sunriseTime)}
                </Text>
            </View>
        </KeyboardAvoidingView>
    );

1 Answer 1

1

The JavaScript compiler error is clear with the error. you are trying to access weather.sys.sunrise object property but not defined/initialized.

It seems that you are trying to fetch weather information of a specific location. If that is the intention of your code.

Refactor code as below :

export const AddressScreen = () => {
  const [address, setAddress] = useState(null);
  const baseURL = `${APIKey}`;

console.log("Fetched weather data:",address)

  const getAddressData = () => {
    axios
      .get(baseURL)
      .then((response) => {

       console.log("Server response:",response)
        setAddress(response.data);
      })
      .catch((error) => console.log(error));
  };

  useEffect(() => {
    getAddressData();
  }, []);

  // Don't access weather data until fetched and assigned to state value.
  if (!address?.sys) return null;

  const sunrise = new Date(address.sys.sunrise * 1000);
  const sunriseTime = sunrise.toLocaleTimeString();

  return (
    <KeyboardAvoidingView>
      <View>
        <Text>Sunrise: {sunriseTime}</Text>
      </View>
    </KeyboardAvoidingView>
  );
};


Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your advice. The error has been fixed, but <Text>Sunrise: {sunriseTime}</Text> has gone maybe because of return null . What problem occurred, and any solutions to fix this?
Try console.log(address) I want to see structure of data after fetched from weather API
Where should I put console.log ?
Check the solution update. I added it for reference
That's great. Glad you figure out.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.