Home > database >  React Component sends [object Object] in request query
React Component sends [object Object] in request query

Time:11-01

I am building a SWAPI app with React and Typescript and my goal is to be able to get information on a specific person when I click on link. My current issue, is that when I try to get data from the api, with the code fragment shown below, I see that instead of passing the id, I am sending [object Object]

const CharacterDetails = (id): JSX.Element => {
  const [character, setCharacter] = useState<any | null>([]);

  const handleCharacterRequest = async (id) => {
    try {
      const results = await getCharacter(id);
      setCharacter(results);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    handleCharacterRequest(id)
  }, [])

However, when I hardcode in the id i want to send, as shown below in the code, the request works fine

const CharacterDetails = (id): JSX.Element => {
  const [character, setCharacter] = useState<any | null>([]);

  const handleCharacterRequest = async (id) => {
    try {
      const results = await getCharacter(id);
      setCharacter(results);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    handleCharacterRequest(1)
  }, [])

The component should be able to receive the ID from the home page, when I click on the entry from the table, by using react-router-dom navigate method:

  const clickHandler = (event: MouseEvent<HTMLElement>) => {
    const { id } = event.target as HTMLElement;
    navigate(`/character/${id}`);
  };

And clicking on this table entry:

<TableCell id={character.id} onClick={(event: any) => clickHandler(event)}>
Id: {character.id}
</TableCell>

What am I missing? Am I setting the wrong parameters?

EDIT: Here is how React Router passes the id for the component, perhaps something here is missing?

<Route path='/character/:id' element={<CharacterDetails />}/>

CodePudding user response:

Found a solution. In my code, I needed to use the useParams() method from react-router-dom.

So the solution looks like this:

const CharacterDetails = (): JSX.Element => {
  const [character, setCharacter] = useState<any | null>([]);

  const { id } = useParams();

  const handleCharacterRequest = async (id) => {
    try {
      const results = await getCharacter(id);
      setCharacter(results);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    console.log(id)
    handleCharacterRequest(id)
  }, [])
  • Related