To display the data from postgraphile api into the react app - javascript

`
import React, { useEffect, useState } from 'react';
import { useQuery, gql } from '#apollo/client';
import { LOAD_USERS } from "../GraphQL/Queries"
function GetUsers() {
const { error, loading, data } = useQuery(LOAD_USERS);
const [users, setUsers] = useState([]);
useEffect(() => {
if (data) {
console.log(data.allUsers)
setUsers(data.allUsers)
}
}, [data]);
return (
<div>
{users.map((val) => {
return <h1> {val.firstname} </h1>
})}
</div>
)
}
export default GetUsers;
`
the error is occuring in console log as
Uncaught TypeError: users.map is not a function. So please help me with this how do i display it on app. it is being print in the console log

Related

ReactJS doesn't display content from array

I fetch data from Firebase and then push that data to array with components. I am trying to display that by using the following code but React displays nothing, also there are no errors in console and during compiling.
import React, { useState ,useEffect } from "react";
import './App.css';
import db from "./firebase";
import { doc, getDocs, getDoc, collection, query, orderBy, limit, where } from "firebase/firestore";
function App() {
useEffect(() => {
getdata();
}, []);
const names = []
async function getdata() {
getDocs(collection(db,'questions')).then((snapshot) => {
snapshot.forEach(doc => {
names.push(<p className="question" >{doc.id}</p>)
Object.values(doc.data()).forEach( test => {
names.push(<p className="answer" >{test}</p>)
});
});
})
}
return (
<div className="App">
{names}
</div>
)
}
export default App;
You need to introduce state into your app.
Put your items into state, and then render JSX from your state
import { collection, getDocs } from 'firebase/firestore';
import React, { useEffect, useState } from 'react';
import './App.css';
import db from './firebase';
function App() {
const [state, setState] = useState([]);
async function getdata() {
const snapshot = await getDocs(collection(db, 'questions'));
const items = [];
snapshot.forEach((doc) => {
items.push({
question: doc.id,
answers: Object.values(doc.data()),
});
});
setState(items);
}
useEffect(() => {
getdata();
}, []);
return (
<div className="App">
{state.map((item) => (
<React.Fragment key={item.question}>
<p className="question">{item.question}</p>
{item.answers.map((answer) => (
<p className="answer" key={answer}>
{answer}
</p>
))}
</React.Fragment>
))}
</div>
);
}
export default App;

Uncaught TypeError: Cannot read properties of undefined (reading 'param')

It's HomePage component of react js
import React from 'react';
import axios from 'axios';
import { useState, useEffect } from 'react';
import { useNavigate,useParams } from 'react-router-dom';
import { Main } from '../components/Main';
import { Controls } from '../components/Controls';
import { ALL_COUNTRIES } from '../config';
import { List } from '../components/List';
import { Card } from '../components/Card';
import { Details } from './Details';
export const HomePage = () => {
const [countries,setCountries] = useState([]);
const navigate = useNavigate();
useEffect(() => {
axios.get(ALL_COUNTRIES).then(({data})=>setCountries(data))
},[]);
return (
<>
<Controls/>
<List>
{
countries.map((c)=>
{
const countryInfo={
img:c.flags.png,
name:c.name,
info: [
{
title:'Population',
description:c.population.toLocaleString(),
},
{
title:'Region',
description:c.region,
},
{
title:'Flag',
description:c.capital,
},
],
};
return <Card key={c.name} onClick={(e)=>{navigate('/country/${c.name}')}}
{...countryInfo}/>
})
}
</List>
</>
);
};
It's second components Details
export const Details = ({match}) => {
return (
<div>
Details {match.param.name}
<div/>
);
};
[https://i.stack.imgur.com/KUyrA.png][before]
HomePage itself looks like this
but when i click on flag/card it sends me on second page as expected but gives me this error
[https://i.stack.imgur.com/JqEHm.png][after]
also i'm using react-router-domV6
and this API https://restcountries.com/v2/all
also both Components are in

Call api on page load in React

I am learning React and I am trying to call an API on my page load, but I haven't had much success so far. I am trying to call an API which will pull an JSON that is used to fill my grid. Here is my code:
import React, { Component, useCallback, useState, useEffect } from "react";
import axios from 'axios';
import './styles.css';
import '#progress/kendo-theme-default/dist/all.css';
import { Grid, GridColumn, GridToolbar } from "#progress/kendo-react-grid";
import { DropDownList } from "#progress/kendo-react-dropdowns";
import { GridPDFExport } from "#progress/kendo-react-pdf";
import { ExcelExport } from "#progress/kendo-react-excel-export";
export function GridTable1({}) {
const [ grid1, setGrid1 ] = useState();
const fillTable= async () => {
await axios
.get('http://11.11.21.111:8888/api/v1/CheckTablespace')
.then((res) => {
setGrid1(res.rlista)
});
console.log('Log this');
}
useEffect(() => {
fillTable();
}, [])
return (
...
...
);
}
The console log isn't logged, so I don't know what to do. Help would be very much appreciated
Try this!!!
export function GridTable1() {
const [ grid1, setGrid1 ] = useState();
useEffect(() => {
axios
.get('http://11.11.21.111:8888/api/v1/CheckTablespace')
.then((res) => {
setGrid1(res.rlista)
});
console.log('Log this');
}, []);
return (
{grid1 &&
<div>
...your HTML
</div>}
);
}

ReactJS rendering Issue fetching an API

I'm trying to fetch a WeatherApp API, using Geolocation.
My problem is the rendering:
It doesn't allow me to render the page before I fetch (but after I somehow manage to fetch, the code seems to work).
Returning Error message:
Type Error : Cannot Read Property 'temp' of undefined
import React, { useState } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
// this line is returning the error
console.log(weather.main.temp)
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
Fetching weather and setting weather state is asynchronous, your are console logging weather.main.temp before the request has completed. And fetching data is side effect in reactjs. So you are suggested to fetch weather info by using useEffect hooks and set weather state there.
import React, { useState, useEffect } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
useEffect(() => {
fetchingWeather();
}, [weather])
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
That should work.

Unhandled Rejection (TypeError): respo.json is not a function

I'm a beginner in React and stuck with some problem. Getting an issue Unhandled Rejection (TypeError): respo.json is not a function.
import React, { useEffect } from "react";
import { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios";
function App() {
const { monster, setMonster } = useState([]);
useEffect(() => {
async function fetchData() {
const respo = await axios.get("https://jsonplaceholder.typicode.com/users");
const resp = await respo.data;
setMonster({ monster: [...resp] });
}
fetchData();
}, [monster]);
return (
<div className="App">
<p>{console.log(monster)}</p>
</div>
);
}
export default App;
Use respo.data instead :
Your response has a data key which you need to fetch.
import React, { useEffect } from 'react';
import {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
function App() {
const [monster,setMonster]=useState([]);
useEffect(()=>{
async function fetchData() {
const respo=await axios.get('https://jsonplaceholder.typicode.com/users')
const resp=await respo.data;
setMonster({monster:[...respo]});
}
fetchData();
},[]);
return (
<div className="App">
<p>{console.log(monster)}</p>
</div>
);
}
export default App;
Working code : https://codesandbox.io/s/elated-platform-1itbi?file=/src/App.js
There are two problems in your code:
const {monster,setMonster}=useState([]);
This should be:
const [monster,setMonster] = useState([]);
const resp = await respo.data;
This should be:
const resp = respo.data;
respo.data is not a promise, but already the result of the api.
Note:
To update monster, you have to call setMonster(resp) not setMonster({ monster: resp })
How about just using get/then instead of async/await?
useEffect(()=>{
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
setMonster({
monster:[...response.data]
});
});
}
},[monster]);

Categories