0

trying to get fetch Data to draw core UI dataTable.

it should be worked when the CButton is clicked.

Here is my question to ask.

sometimes the data is stored in const data and sometimes the data is undefined. is this because the method is async?

to prevent it, should I use useEffect()? something like

useEffect(
    () => {
      getData()
    },
    [data]
  );

Here is my codes.

const vertification = () => {

...
...some Code
...

// main parts for Axios
  const [query, setQuery] = useState("");
  const [data, setData] = useState();
 
  //test API  
  const url = `https://pokeapi.co/api/v2/pokemon`;

  const getData = async ()  => {
    if(query !== "") {
      const result = await Axios.get(url).then(
        response => {
          setData(response.data.results);
        }
      );
        
      //to check, whether the data is undefined or not.
      console.log("The Data from the hooks is :", data);
      setQuery("");
    } else {
      console.log("Please fill the form for me");
    }
  }
  
  const onChange = (e) => {
    console.log("the Value: ", e.target.value);
      setQuery(e.target.value);
  }
  const onSubmit = (e) => {
    e.preventDefault();
    getData();
  }
   return (
    ...
    ...
    <CButton type="submit" size="sm" onClick={onSubmit} color="success">Submit</CButton>
    ...
   )
}
export default vertification;


Jin Park
  • 371
  • 1
  • 9
  • 23

1 Answers1

0

Its all correct just your console log is before changing state, just put them inside response function:

const getData = () => {
  if (query !== "") {
    Axios.get(url).then((response) => {
      setData(response.data.results);
      //to check, whether the data is undefined or not.
      console.log("The Data from the hooks is :", response.data.results);
      setQuery("");
    });
  } else {
    console.log("Please fill the form for me");
  }
};
b3hr4d
  • 4,012
  • 1
  • 11
  • 24