How to get json response in react.js from laravel?

by darrion.kuhn , in category: PHP Frameworks , 10 months ago

How to get json response in react.js from laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 6 months ago

@darrion.kuhn 

To get a JSON response from a Laravel backend in a React.js frontend, you can make an HTTP request to the backend API using the fetch() method or Axios library. Here is an example using fetch():

  1. In your React component, import the fetch() method:
1
import React, { useEffect, useState } from 'react';


  1. Use the fetch() method to make an HTTP request to the Laravel backend API endpoint that returns a JSON response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('http://your-api-endpoint.com/api/data');
      const responseData = await response.json();

      setData(responseData);
    }

    fetchData();
  }, []);

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
}

export default MyComponent;


  1. Replace 'http://your-api-endpoint.com/api/data' with the actual endpoint of your Laravel backend API that returns a JSON response.
  2. In your Laravel backend, make sure to return the data in JSON format in the specified endpoint:
1
2
3
4
5
6
public function getData()
{
    $data = YourModel::all();

    return response()->json($data);
}


Now, when you access the React component that makes the fetch request, it should display the JSON data returned from the Laravel backend API.

Related Threads:

How to remove slashes from json response in laravel?
How to get data from json file using name in url in react.js?
How to get json from request in laravel?
How to get json post request in laravel?
How to format a json response in php?
How to return image and json in one response in fastapi?