React, local json file won't display - javascript

I have a local json which is returning all values on console.log so I know the path is correct. However when I am trying to pull an input value of name from it, it gives me error uni.map is not a function.
What am I'm missing, any help will be fab :).
import { useState } from 'react'
import axios from 'axios'
import Uni from './Uni'
function Unis() {
const [unis, setUnis] = useState([])
const [query, setQuery] = useState('')
function handleSearchQuery(e) {
e.preventDefault()
setQuery(e.target.value)
}
async function searchUnis(e) {
e.preventDefault()
console.log()
var response = await axios.get(data.json)
setUnis(response.data)
}
return (
<div>
<input value={query} onChange={handleSearchQuery} />
<button onClick={searchUnis}>Search</button>
<ul>
{
unis.map(function(i, index){
return (
<li key={index}>
<Uni name={i.name} />
</li>
)
})
}
</ul>
</div>
)
}
export default Unis;
data.json
{
"data": [
{
"name": "xxx",
"years": "2022"
},
{
"name": "hhh",
"years": "2021"
}
]
}

Good Luck,
You have used data.json directly without import.
var response = await axios.get(data.json)
Ans:
Step 1:
Import the data.json file in Unis file.
import Data from './data.json';
Step 2:
Use the data like below.
var response = await axios.get(Data.data);

Related

I want to fetch my orders data from the service file, but there is an error that im not successful to solve

the error in the console is :
ERROR in [eslint]
src\services\orders.js
Line 9:3: Expected an assignment or function call and instead saw an expression no-unused-expressions
Search for the keywords to learn more about each error.
app.jsx
import { useEffect, useState } from 'react';
import './App.css';
import { Table } from './components/Table';
import {ordersService} from './services/ordersService'
function App() {
const [orders , setOrders] = useState(null)
useEffect(() => {
async function fetchData() {
const ordersData = await ordersService.query();
console.log(ordersData);
}
fetchData();
}, []);
return (
<div className="app">
<Table orders={ orders } />
</div>
);
}
services\ordersService.js
export const ordersService = {
query
}
function query(sortBy) {
return Promise.resolve(gOrders)
}
const gOrders = [{
"order_ID": 2790846857303,
"name": "#38777",
"total_refunded": 0,
"created_at": "2020-11-23 23:27:52",

Axios not fetching data using Reactjs

I am working with Reactjs/nextjs and i am trying to fetch data using "Axios", In "Api url" data is fetching/showing but in my webpage showing "There are no records yet",Where i am wrong ? Here is my current code
import React from 'react'
import { useEffect, useState } from "react";
import axios from 'axios';
function Displaydata() {
const [posts,setPosts]=useState([]);
useEffect(()=>
{
const getdata=async()=>
{
const { data: res } = await axios.get(
"xxxxxxxxxxxxxxxxxxxx/api/Allvideo"
);
console.log(res);
setPosts(res);
};
})
return(
<div>
{posts?.length ? posts.map((product: { id: any; link: any; }) => <p key={product.id}>
{product.id}-{product.link}</p>)
: <h3>There are no records yet</h3>}
</div>
)
}
export default Displaydata
We need to pass second argument for useEffect as empty array or array of values. and then getdata function declared but not called. please find the below code.
useEffect(() => {
const getdata = async() => {
const { data: res } = await axios.get("xxxxxxxxxxxxxxxxxxxx/api/Allvideo");
console.log(res);
setPosts(res);
};
getdata();
}, []);
hope this helps!!!

How can I fetch data from Firebase into my React App

Please, I am very new to React.js and having this challenge of fetching dating from Firebase to populate this. I want to be able to fetch a single properties and not all of them - eg (title, body and price).
useFetch is a custom hook I created inside the project to handle the fetch from firebase.
What am I not getting right here please?
import { useParams } from 'react-router-dom';
import useFetch from '../UseFetch';
import '../courseDetails/CourseDetails.css';
import { useState, useEffect } from 'react';
import React from 'react'
const CourseDetails = () => {
const { id } = useParams();
const { data:details, isLoading } = useFetch('https://tutorialwebsite-460f1-default-rtdb.firebaseio.com/courses.json');
console.log(details);
return (
<div className="course-detail">
<h2>{ id }</h2>
<div>
<p>{details.description}</p>
</div>
</div>
)
}
export default CourseDetails
Here's the object loaded from the API:
{
"-MaebRkqKfjLG8heBbSu": {
"body": "qwerqwer",
"description": "wqerqwetqwe",
"imageUrl": "wdfwerw",
"price": "werqwertwer",
"title": "title 1"
}
}
How can I access the description?
Thank you everyone for your response but I was able to solve my problem. So what I did was changed into a used fake json api instead of firebase I was initially using. Then I was able to dynamically route to a specific page based of the unique id after fetching the data from firebase and then used conditional rendering to output the data on the page. However, I would have loved to know how to do this using using firebase.
const CourseDetails = () => {
const { id } = useParams();
const { data:details, isLoading } = useFetch('http://localhost:8000/courses/' + id);
console.log(details)
return (
<div className="course-detail">
{isLoading && <div>Loading...</div>}
{details && <div>{details.body}</div> }
</div>
)
}
export default CourseDetails

Get items by name from JSON based on user input id react

Hey how would I go about getting items by name from a JSON file based on what a user inputs? I have a JSON file that has an id and name. I want the user to put in a number and then display the item name associated with that id number. I am using ReactJS for this. Any advice would be greatly appreciated. thank you
You can read JSON file as Javascript Object or Array.
I use react hooks. Sorry my English very bad.
import { useState } from 'react';
import jsonData from './data.json';
export default function Test() {
const [name, setName] = useState('');
const onChange = (e) => {
// jsonData is javascript array when import it
const data = jsonData.find((d) => d.id == e.target.value);
if (data) {
setName(data.name);
}
};
return (
<div>
<input onChange={onChange} />
<p>Name: {name}</p>
</div>
);
}
JSON file for test:
[
{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "def"
},
{
"id": 3,
"name": "ghi"
}
]

Problem with using deeper nested data fetched from API

I encountered a problem when I try to fetch some data from PokeAPI. Here's my code for PokemonCard component.
import React, { useEffect, useState } from "react";
import axios from "axios";
const PokemonCard = ({ pokemonID }) => {
const [pokemon, setPokemon] = useState({});
useEffect(() => {
(async () => {
const result = await axios.get(
`http://pokeapi.co/api/v2/pokemon/${pokemonID + 1}`
);
setPokemon(result.data);
})();
// console.log(pokemon.weight)
}, [pokemonID]);
return (
<div className="pokemon">
{pokemon.sprites.front_default}
</div>
);
};
export default PokemonCard;
Everything works properly when I try to reach data like: pokemon.weight or pokemon.base_experience. But I get errors when I try to use some deeper nested variables.
pokemon.sprites.front_default gives me an error TypeError:
Cannot read property 'front_default' of undefined.
Here's a sample of data from API:
"name": "bulbasaur",
"order": 1,
"species": {
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon-species/1/"
},
"sprites": {
"back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/1.png",
"back_female": null,
"back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/1.png",
"back_shiny_female": null,
"front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
"front_female": null,
"front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png",
"front_shiny_female": null
},
"stats": [
{
"base_stat": 45,
"effort": 0,
"stat": {
"name": "hp",
"url": "https://pokeapi.co/api/v2/stat/1/"
}
}
],
"types": [
{
"slot": 2,
"type": {
"name": "poison",
"url": "https://pokeapi.co/api/v2/type/4/"
}
},
{
"slot": 1,
"type": {
"name": "grass",
"url": "https://pokeapi.co/api/v2/type/12/"
}
}
],
"weight": 69
PS. Is it a good practice to make about 150 separate calls to API in every child component? Or should I somehow do it with one call? Thank you.
You were trying to access a key inside an undefined key of pokemon variable. Please check the updated line where you are actually rendering.
{pokemon.sprites ? pokemon.sprites.front_default : ''}
As Pokemon is an empty object before the api fetches the data and
updates to the state, so pokemon.sprites is actually undefined.
import React, { useEffect, useState } from "react";
import axios from "axios";
const PokemonCard = ({ pokemonID }) => {
const [pokemon, setPokemon] = useState({});
useEffect(() => {
(async () => {
const result = await axios.get(
`http://pokeapi.co/api/v2/pokemon/${pokemonID + 1}`
);
setPokemon(result.data);
})();
// console.log(pokemon.weight)
}, [pokemonID]);
return (
<div className="pokemon">
//this should work for you
{pokemon.sprites ? pokemon.sprites.front_default : ''}
</div>
);
};
export default PokemonCard;
Gets much easier in Optional chaining (?.)
pokemon.sprites?.front_default

Categories