skip to Main Content

When I refreshed the page my app crashes. This was due to my page loading in faster than my data. I think… SO I added additional checks using the logical AND (&&) operator. Is this best practice? It just seems odd to have to do this everywhere. Is there a better, more practical way around this?

I was just messing around with how I fetch APIs. This isn’t from any special project of mine just a little sandbox file.

This is what the code looked like when it was crashing on page refresh…

import React, { useEffect, useState } from "react";
import { Heading } from "./components/Heading";

const URL = "https://api.sleeper.app/v1/league/867824542855376896";

function App() {
  const [data, setData] = useState(null);

  const getData = async () => {
    try {
      const res = await fetch(URL);
      const data = await res.json();
      setData(data);
    } catch (err) {
      console.log(err);
    }
  };

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

  console.log(data);
  return (
    <>
      <Heading str="Hello world" />
      <Heading str="Hello friend" />
      <h1>{data.bracket_id}</h1>
      {data.roster_positions.map((pos, i) => {
          return <h1 key={i + 1}>{pos}</h1>;
        })}
    </>
  );
}

export default App;

And this is what I did to fix it…

import React, { useEffect, useState } from "react";
import { Heading } from "./components/Heading";

const URL = "https://api.sleeper.app/v1/league/867824542855376896";

function App() {
  const [data, setData] = useState(null);

  const getData = async () => {
    try {
      const res = await fetch(URL);
      const data = await res.json();
      setData(data);
    } catch (err) {
      console.log(err);
    }
  };

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

  console.log(data);
  return (
    <>
      <Heading str="Hello world" />
      <Heading str="Hello friend" />
      <h1>{data && data.bracket_id}</h1>
      {data &&
        data.roster_positions.map((pos, i) => {
          return <h1 key={i + 1}>{pos}</h1>;
        })}
    </>
  );
}

export default App;

Is there a better way of doing this beside add a logical AND operator before every use of my data?

2

Answers


  1. Here I Have Made Some Update on Your Code On Mine Experience Which i have faced issue previously so i write code like this

    import React, { useEffect, useState } from "react";
    import { Heading } from "./components/Heading";
    
    const URL = "https://api.sleeper.app/v1/league/867824542855376896";
    
    function App() {
      const [data, setData] = useState({}); // instead of using null use {}
      // Some Time Function Call inside useEffect Become A Cause of Error
    
      useEffect(() => {
        const getData = async () => {
        try {
          const res = await fetch(URL);
          const data = await res.json();
          setData(data);
        } catch (err) {
          console.log(err);
        }
      };
        // Add Condition Here
        if ( data === {} && data.length === 0 ) {
           getData();
           console.log(data);
        }
        
      }, []); // Add Rest Dependency Here
    
      
      return (
        <>
          <Heading str="Hello world" />
          <Heading str="Hello friend" />
          <h1>{data && data.bracket_id}</h1>
          {data && data.length > 0 &&
            data?.roster_positions.map((pos, i) => {
              return <h1 key={i + 1}>{pos}</h1>;
            })}
        </>
      );
    }
    
    export default App;
    

    I You Like This way Then You Can Follow It

    Login or Signup to reply.
  2. A combination of conditionals and Array can be used.
    This is what I came out with after an hour of trial and error

    if(data){
        return [ //<---yes, array
          // When using arrays, each element should have a key (even single <h1's> like this
          <h1 key="bracket_id">{data.bracket_id}</h1>,
          <ul key="roster_positions">{data.roster_positions.map((pos, i) => {
                return <li key={i + 1}>{pos}</li>;
              })
           }</ul>
        ];
      } else {
        return <h1>loading</h1>
      }
    

    Based on How to concatenate two JSX fragment or variables or string and component (in Reactjs)?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search