Home > Net >  React JS/Typescript Axios Variable Assignment
React JS/Typescript Axios Variable Assignment

Time:09-27

React JS, Axios, "response.data.title" is successfully returned in the get operation I have done with axios. However, when I assign it to the title variable and want to show {title} on the screen, nothing appears. There is a problem with the value assignments.

import React, { FC, constructor, useEffect } from 'react'
import axios, { AxiosResponse, AxiosError } from "axios";

interface HowToContactAShopProps {
   title: string
}

const HowToContactAShop: FC<HowToContactAShopProps> = ({ title }) => {

   useEffect(() => {
      axios.get('http://localhost:1337/reviews/1')
     .then((response: AxiosResponse) => {
        title = response.data.title
        console.log(title);
    });
  });

 return (

    <NavbarLayout>

      <H1>How to Contact a Shop</H1>
      <H1>{title}</H1>

  </NavbarLayout>
 )
}
export default HowToContactAShop

CodePudding user response:

Make title variable state variable and update title using set state method.

interface HowToContactAShopProps {
}

const HowToContactAShop: FC<HowToContactAShopProps> = () => {
   const [title, setTitle] = useState<string>('');
   useEffect(() => {
      axios.get('http://localhost:1337/reviews/1')
     .then((response: AxiosResponse) => {
        setTitle(response.data.title)
    });
  }, []);

 return (

    <NavbarLayout>

      <H1>How to Contact a Shop</H1>
      <H1>{title}</H1>

  </NavbarLayout>
 )
}

CodePudding user response:

Apart from managing the state, it's essential to keep empty dependency array on useEffect. Otherwise, it will re-render the component infinitely.

import React, { FC, constructor, useEffect, useState } from 'react'
import axios, { AxiosResponse, AxiosError } from "axios";

interface HowToContactAShopProps {
   title: string
}

const HowToContactAShop: FC<HowToContactAShopProps> = ({ title }) => {

    const const [title, setTitle] = useState<string>("");

   useEffect(() => {
      axios.get('http://localhost:1337/reviews/1')
     .then((response: AxiosResponse) => {
        setTitle(response.data.title);
        console.log(title);
    });
  },[]);

 return (

    <NavbarLayout>

      <H1>How to Contact a Shop</H1>
      <H1>{title}</H1>

  </NavbarLayout>
 )
}
export default HowToContactAShop
  • Related