skip to Main Content

Hey guys thanks for your time. I’m still new to React so I’m trying to learn how to use it. I’m retrieving items from an API and after I’m getting a success, I push the setState to create the new components from the response – and I don’t have any problems with that.
But I was trying to render two different components, one for the loading state when we are waiting for a response from the server, and the actual elements. And I know there is a way to do it with a ternary condition. But I think an anonymous function looks better. And this works well with the "Loading…" state, but after I get the response from the server, it doesn’t display anything. If I’ll throw even static data there – it doesn’t show. How this thing works like? Cause If I’ll debug each element in map – I’ll have my response – but It just don’t want to render them.

export function Main(){

  const [state, setState] = useState({users: []});
  const temporaryUsers = state.users;
  useEffect(() => {
      fetch(`https://randomuser.me/api/?results=20`)
      .then(res => res.json())
      .then(json => {
        temporaryUsers.push(json);
        setState({
          users: temporaryUsers
        });
      });
        
    },[])
  
      return(
        <>
          {(() => {
            if (state.users[0] != undefined){
              state.users[0].results.map((elem) => {
                return(
                  <User  props={elem} />
                )
              })
              
            } else{
              return (
                <p style={{textAlign:"center", display:"block", width:"100%"}}>Loading...</p>
              ) 
            }
          })()}
        </>
        
      )
  
}

2

Answers


  1. Update:
    Implemented it in react playground here using static data with delay.


    Instead of directly modifying the temporaryUsers array and pushing the response, you should create a new array with the response data and then update the state using that new array.

    export function Main() {
      const [state, setState] = useState({ users: [] });
    
      useEffect(() => {
        fetch("https://randomuser.me/api/?results=20")
          .then((res) => res.json())
          .then((json) => {
            setState({ users: json.results });
          });
      }, []);
    
      return (
        <>
          {state.users.length > 0 ? (
            state.users.map((elem) => <User key={elem.id} props={elem} />)
          ) : (
            <p style={{ textAlign: "center", display: "block", width: "100%" }}>
              Loading...
            </p>
          )}
        </>
      );
    }
    
    
    Login or Signup to reply.
  2. The map loop should be:

    state.users[0].results.map((elem) =>(
                  <User  props={elem} />
                ))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search