Home > Mobile >  React and Next map returning undefined
React and Next map returning undefined

Time:04-26

So I have been working with NextAuth for a few hours and have been using the Twitter API to login/search for tweets

I have got most of the things set up with ease however there's some issues with my client side fetching oof the API routes I created on the server.

Index.js

export default function Home() {
const { data: session } = useSession()
  const [statuses, setStatuses] = useState();


 useEffect(() => {
    
 fetch('api/twitter/search')
 .then(response => response.json(),)
 .then(response => setStatuses(response))
 .catch(err => console.error(err));

 console.log(statuses)

  
 }, [])



 
 



  if (session) {
    return (
      <>
      Welcome {session.user.name}<br/>
        Signed in as {session.user.email} <br />
 
      
        {statuses.map((st) => (
         <p>{st.data.id}</p>
))}


        <button onClick={() => signOut()}>Sign out</button>
      </>
    )
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn()}>Sign in</button>
    </>
  )
  

  
}

export async function getServerSideProps(context) {
  return {
    props: {
      session: await getSession(context),
    },
  }
}

I keep getting the error cannot read properties of undefined (reading 'map')

Even tho I have checked in my React dev tools that the statuses state indeed has the data I'm trying to map over.

EDIT - console.log of statuses

console.log(statuses)

CodePudding user response:

Initialize your state for statuses to be an empty array. React is trying to render before your api call has completed.

const [statuses, setStatuses] = useState([]);

CodePudding user response:

export default function Home() {
const { data: session } = useSession()
  const [statuses, setStatuses] = useState([]);


 useEffect(() => {
    
 fetch('api/twitter/search')
 .then(response => response.json(),)
 .then(response => setStatuses(response?.data))
 .catch(err => console.error(err));

 console.log(statuses)

  
 }, [])


    return (
    <>
      {session && 
        <>
          Welcome {session?.user?.name}<br/>
          Signed in as {session?.user?.email} <br />
          {statuses?.map((st) => (<p>{st?.id}</p>))}
          <button onClick={() => signOut()}>Sign out</button>
        </>
       }
      {!session &&
        <>
          Not signed in <br />
          <button onClick={() => signIn()}>Sign in</button>
        </>
    </>
    )
}

export async function getServerSideProps(context) {
  return {
    props: {
      session: await getSession(context),
    },
  }
}

You are getting session value before your state is being set inside the useEffect. Adding ? before map would remove the error statuses?.map

  • Related