0

Code of Sword Component:

import { useSession } from "next-auth/react";
import fetch from "isomorphic-unfetch";

const Sword = () => {
  const getUser = async () => {
    const { data: session } = await useSession();
    const res = await fetch(
      `http://localhost:3000/api/${(session?.user as any).id}`
    );
    const data = await res.json();
    return { user: data };
  };
  const user: any = getUser().then((res: any) => {
    console.log(res.user.name);
  });
  return (
    <div>
      <h1>Sword</h1>
      <p>Name: {user.name}</p>
    </div>
  );
};

export default Sword;

The console log on the constant user displays the actual name, but when trying to use it down it doesn't display anything. And when using user.user.name I get an error. How may I fix this issue?enter image description here

Also when trying to use

  console.log(user.name)

below the user constant, it outputs undefined.

FSCYT
  • 104
  • 7
  • Do you have any store defined? If not, you need to define some store and use useEffect, useState hooks to achieve your results – Alopwer Jul 14 '22 at 09:19
  • @Alopwer and how may I go on doing that, do you have any tutorial that you can link to help with my issue? – FSCYT Jul 14 '22 at 09:25
  • google for redux js, I'll leave the implementation of component in the answer, you'll just have to define the store – Alopwer Jul 14 '22 at 09:26
  • 2
    Redux is not at all required for this. – Nicholas Tower Jul 14 '22 at 09:31
  • @NicholasTower I've figured so, this isn't that complicated and I've done it before without the use of Redux. – FSCYT Jul 14 '22 at 09:32

2 Answers2

1

The updated component:

export const Sword = () => {
  const dispatch = useDispatch()
  const user = useSelector(state => state.user)

  useEffect(() => {
    dispatch(getUser)
  }, [])

  return <div>
    <h1>{{ user.name }}</h1>
  </div>
}

getUser should be a thunk action

Alopwer
  • 611
  • 8
  • 22
1

New code to fix the issue:

import { useSession } from "next-auth/react";
import fetch from "isomorphic-unfetch";
import { useEffect, useState } from "react";

const Sword = () => {
  const [name, setName] = useState("");
  const { data: session } = useSession();
  useEffect(() => {
    const getUser = async () => {
      const res = await fetch(
        `http://localhost:3000/api/${(session?.user as any).id}`
      );
      const data = await res.json();
      setName(data.name);
      return { user: data };
    };
    getUser();
  }, []);
  return (
    <div>
      <h1>Sword</h1>
      <p>{name}</p>
    </div>
  );
};

export default Sword;

Basically I've wrapped my function in a useEffect and used useState to set and get the name of the user, doing so seems to have fixed the issue. Solution of my problem

Thanks to @Alopwer for letting me know what to do.

FSCYT
  • 104
  • 7