I am building a wordpress plugin in which I have implement a widget which shows analytics chart from the wordpress data table named dummy using rest api but I am failing to do so. I am using reactjs for building plugin and axios for fetching data from database and recharts for showing analytics chart.
import React from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import axios from 'axios';
const API_URL = "http://localhost/wordpress2/wp-json/wp/v2?query=dummy"
const Dashboard = () => {
axios.get(API_URL)
.then(Response => {console.log(Response.data);
}).catch(err => console.log(err));
return (
<div className='dashboard' >
<div className="card" >
<h3>Analytics</h3>
<ResponsiveContainer>
<LineChart data={Response}>
<XAxis dataKey="post" />
<YAxis />
<Legend/>
<Tooltip />
<CartesianGrid stroke="#eee" />
<Line type="monotone" dataKey="likes" stroke="#8884d8" />
<Line type="monotone" dataKey="dislikes" stroke="#82ca9d" />
</LineChart>
</ResponsiveContainer>
</div>
</div>
);
}
export default Dashboard;
In my wordpress dashboard plugin is working well and chart is also showing but without data it will show when apiurl problem is solved.
3
Answers
Hey @Jit you need to call axios inside useEffect hook like-
try this code, if you still facing issue lemme know. I will help you more.
Thanks
so normally you have to see your data in the console beside i suggest you to do it into the useEffect hook (see @varun-kaklia response) . Btw, you have to store you data somewhere in order to use it (here with your LineChart component).
What i suggest you to do is to store you data in the easiest store in react : the useState.
I went through your code and found some errors in that. Try this code for calling the API