Array using useState React.Js Hooks

Asked

Viewed 450 times

0

I’m having a problem with a project I’m using React.js, and axios for consumption of API

const [id, setId] = useState('');
const [image, setImage] = useState('');
const [att, setAtt] = useState(0);
const [nameCorrect, setNameCorrect] = useState('');
const [type, setType] = useState([])

useEffect(() => {
    api.get(props.name)
        .then(res => {
            setId(res.data.id);
            setImage(res.data.sprites.front_default);
            setType(res.data.types)            
            setNameCorrect(props
               .name
               .substring(0,1)
               .toUpperCase()
               .concat(props.name.substring(1))
            );
        })

On the line of setType(res.data.types) basically is not guarding the array with the data in constante type

This is the link of the api I’m using, if you notice have types within the date I’m looking for https://pokeapi.co/api/v2/pokemon/1/

Note: when giving a console.log in the types he returns arrays empty.

  • It depends on where you are giving console.log in to type, if it’s inside the useEffect that runs non-stop will never see any update.

1 answer

1

I made a test in the Codesandbox and apparently it worked, I’m assuming that useEffect is executed only once, with useEffect(() => {}, []). Note to the [] (empty array) as second parameter.

I left the method setNameCorrect commented, because it depends on the props of its component.

import React, { useEffect, useState } from "react";
import "./styles.css";
import * as api from "axios";

export default function App(props) {
  const [id, setId] = useState("");
  const [image, setImage] = useState("");
  const [att, setAtt] = useState(0);
  const [nameCorrect, setNameCorrect] = useState("");
  const [type, setType] = useState([]);

  useEffect(() => {
api
  .get("https://pokeapi.co/api/v2/pokemon/1/")
  .then(({ data }) => {
    setId(data.id);
    setImage(data.sprites.front_default);

    setType(data.types);

    // setNameCorrect(
    //   props.name.substring(0, 1).toUpperCase().concat(props.name.substring(1))
    // );
  })
  .catch((err) => console.error(err));
  }, []);

  useEffect(() => {
console.log("Type value", type);
  });

  return (
<div className="App">
  <h1>{type && type.length} types</h1>
</div>
  );
}

I added destructuring on the return of Promise to improve the syntax, but the result will be the same.

  • I tried using your code, I copied it exactly, but it keeps giving problems, when I save it brings the information, but as soon as I give an F5 or restart the server, it stops bringing the result to me, it simply returns the empty arrays. Just the moment I save the code after it’s changed it brings me the data.

  • What is causing confusion for you is the console.log below data retrieval. It is logging in as an empty array, but in fact its view already has the value. Not necessarily at the time you log setType has just been executed, this is the balcony of using Hooks. I edited my reply by adding another hook to asynchronously display the log result and for better understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.