Home > Software engineering >  when re rendering react, object is null
when re rendering react, object is null

Time:11-18

im calling an object from the pokeapi, exactly the name property and on first render after saving the file i get the name but i dont know why, re render and then the propertie is null and i get an error

this is my component card

import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import { Avatar, Card, Col, Row } from "antd";

function Pokecard(values: any) {
  const { response} = values;

  const { Meta } = Card;
  return (
    <Row gutter={[10, 10]}>
        <Col>
          <Card
            style={{ width: 300 }}
            cover={
              <img
                alt={"" }
                src={response && response['sprites']['front_default']}
              />
            }
            actions={[
              <SettingOutlined key="setting" />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={response.name}
              description=""
            />
          </Card>
        </Col>
    </Row>
  );
}

export default Pokecard;

this is my view

import { Methods } from "../interfaces/request";
import { useEffect, useState } from "react";
import Pokecard from "../components/pokecard/Pokecard";
import useAxios from "../plugins/Useaxios";

function App2() {
  const { response, loading, error } = useAxios({
    method: Methods["get"],
    url: "/ditto",
    body: JSON.stringify({}),
    headers: JSON.stringify({}),
  });
  const [data, setData] = useState([]);

  useEffect(() => {
    if (response !== null) {
      setData(response);
    }
  }, [response]);
  let args: any = {
    response,
  };
  return (
    <>
      <Pokecard {...args} />;
    </>
  );
}

export default App2;

import { Methods } from "../interfaces/request";
import { useEffect, useState } from "react";
import Pokecard from "../components/pokecard/Pokecard";
import useAxios from "../plugins/Useaxios";

function App2() {
  const { response, loading, error } = useAxios({
    method: Methods["get"],
    url: "/ditto",
    body: JSON.stringify({}),
    headers: JSON.stringify({}),
  });
  const [data, setData] = useState([]);

  useEffect(() => {
    if (response !== null) {
      setData(response);
    }
  }, [response]);
  let args: any = {
    response,
  };
  return (
    <>
      <Pokecard {...args} />;
    </>
  );
}

export default App2;

and this is my plugin axios

import axios from "axios";
import Request from "../interfaces/request";
import { useState, useEffect } from "react";
enum Methods {
  get = "get",
  post = "post",
  default = "get",
}

const useAxios = ({ url, method, body, headers }: Request) => {
  axios.defaults.baseURL = "https://pokeapi.co/api/v2/pokemon";
  const [response, setResponse] = useState(null);
  const [error, setError] = useState("");
  const [loading, setloading] = useState(true);

  const fetchData = () => {
    axios[method](url, JSON.parse(headers), JSON.parse(body))
      .then((res: any) => {
        setResponse(res.data);
      })
      .catch((err: any) => {
        setError(err);
      })
      .finally(() => {
        setloading(false);
      });
  };

  useEffect(() => {
    fetchData();
  }, [method, url, body, headers]);

  return { response, error, loading };
};

export default useAxios;

im learning to destructuring objects

im tried saving the object in the store but i got an Undifined

sorry for my english

CodePudding user response:

you can try something like this

title={response?.name || ''}

CodePudding user response:

Try using the resonse directly

 const { response, loading, error } = useAxios({
    method: Methods["get"],
    url: "/ditto",
    body: JSON.stringify({}),
    headers: JSON.stringify({}),
  });

  const name = response?.name;

  const src = response?.sprites?.?front_default;

  // use the properties directly inside the child
  return (
    <>
      <Pokecard name={name} src={src}/> 
    </>
  );

You can check examples of how when useEffect is not needed

  • Related