0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js / React + Axios – JSX に変数の中身を表示するには useState が必要のようだ

Last updated at Posted at 2023-01-04

動かない例

axios get の値をそのまま変数として利用しようとした場合

console.log では値が得られるが
画面には表示されない

import axios from "axios";

const AxiosGet = () => {
  const fetchURL: string = "https://jsonplaceholder.typicode.com/posts/1";

  var post;

    axios.get(fetchURL).then((response) => {
      post = response.data;
      console.log(post)
    });

  if (!post) return null;

  return (
    <div>
      <h1>{post['title']}</h1>
      <p>{post['body']}</p>
    </div>
  );
}

export default AxiosGet;

動く例

動かすには変数を useState の器に入れてやる必要がある
おそらくaxiosの非同期処理が関係しているのではないだろうか

import axios from "axios";
import React from 'react'

const AxiosGet = () => {
  const baseURL = "https://jsonplaceholder.typicode.com/posts/1";
  const [post, setPost] = React.useState(null);

  React.useEffect(() => {
    axios.get(baseURL).then((response) => {
      setPost(response.data);
    });
  }, []);

  if (!post) return null;

  return (
    <div>
      <h1>{post['title']}</h1>
      <p>{post['body']}</p>
    </div>
  );
}

export default AxiosGet;

環境

next@13.1.1

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?