How can i passing id which match? - javascript

I'm new to ReactJS, please don't judge me.
So I fetch some user and I want to display them one by one, but as you can see in this picture I don't get the ID, but I get the id in the iteration
import React, { useState, useEffect } from 'react';
import '../App.css';
import { Link } from 'react-router-dom';
function Users() {
useEffect(() => {
fetchItems();
}, []);
const [items, setItems] = useState([]);
const fetchItems = async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/users');
const items = await data.json();
console.log(items.id);
setItems(items);
};
return (
<div>
{items.map(item => (
<h1 key={item.id}>
<Link to={`/users/${item.id}`}>{item.name}</Link>
</h1>
))}
</div>
);
}
export default Users;
and here is my UserDetails :
import React, { useState, useEffect } from 'react';
import '../App.css';
function UserDetail({ match }) {
useEffect(() => {
fetchItem();
console.log(match.id);
}, [match]);
const [user, userItem] = useState({});
const fetchItem = async () => {
const data = await fetch(
`https://jsonplaceholder.typicode.com/users/${match.id}`
);
const user = await data.json();
console.log(user);
};
return (
<div>
<h1>Item</h1>
</div>
);
}
export default UserDetail;
and i get this error.
I dont' get my id,and i don't know why.

Related

jest not able to findbyTestID with async await

I am getting error : Unable to find an element by: [data-testid="postLists"]
My ReactJS code is:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const AwaitAsync2 = () => {
const [posts, setPosts] = useState(null);
useEffect(() => {
postApi();
}, []);
const postApi = async () => {
const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts');
setPosts(data);
}
return (
<div>
<h2>Await Async</h2>
{
posts !== null && (<div data-testid="postLists">
{
posts.map((item, index) => {
return <div key={index}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</div>
})
}
</div>)
}
</div>
)
}
and unit test case is
import { render, screen } from "#testing-library/react";
import AwaitAsync2 from "./aa2";
describe("Async Await 2 testing", () => {
it("API Testing", async () => {
render(<AwaitAsync2 />);
const data = await screen.findByTestId("postLists");
expect(data).toBeInTheDocument();
});
});
getting an error for this line
await screen.findByTestId("postLists");

how to fetch data according to slug in ReactJS?

I'm trying to fetch the particular blog according to the slug but I'm getting a axios error of 404 not found. i would really appreciate if any one can help..
import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
const data = "https://bulkaccounts.com/api/blogs";
function Singleblog() {
const { slug } = useParams();
const [blog, setBlog] = useState({});
const [isloading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [items, setItems] = useState(null);
useEffect(() => {
const fetchBlogBySlug = async () => {
setIsLoading(true);
try {
const res = await axios.get(`http://localhost:3000/blog/${slug}`);
console.log({ res });
if (res?.data?.data) {
setBlog(res.data.data);
} else {
setError("Blog not found.");
}
} catch (error) {
console.log(error);
setError("Blog not found.");
}
setIsLoading(false);
};
fetchBlogBySlug();
}, [slug]);
let showData = "";
showData = (
<>
<div className="blog">
{data &&
data.datas.data.map((item) => {
return (
<>
<div className="flex-container">
<div className="card">hello</div>
</div>
</>
);
})}
</div>
</>
);
return (
<>
{showData}
<Link to="/">Home</Link>
</>
);
}
export default Singleblog;
// Api = https://bulkaccounts.com/api/blogs
i tried that code but it doesn't worked for me. help me figure out my mistake
First, check if http://localhost:3000/blog is a valid back-end server URL.
I think replacing http://localhost:3000/blog with https://bulkaccounts.com/api/blogs will solve the problem.

How to get data using async await?

How to get the data correctly
import { NextApiHandler } from "next";
import data from "../../../lib/data.json";
const cars: NextApiHandler = (_req, res) => {
res.status(200).json(data);
};
export default cars;
I tried to use async await for getting data but something went wrong. When I`m trying to print in console.log what is "cars" it returns me function instead of promise.
You can try this way to get data
import React, { useEffect, useState } from 'react';
import Item from '../Item/Item';
const Items = () => {
const [items, setItems] = useState([]);
useEffect( ()=>{
fetch('http://localhost:5000/items')
.then(res => res.json())
.then(data => setItems(data));
}, [])
return (
<div id='items' className='container'>
<h1 className='item-title'>Items For You</h1>
<div className="items-container">
{
items.map(item => <Item
key={item._id}
item={item}
>
</Item>)
}
</div>
</div>
);
};
export default Items;

fetch dosent bring any data

when i use fetch to bring the list of notes and consol.log it nothing shows up. The url is not wrong i have carefully checked it. Here is the code:
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
here is the api part:
#api_view(['GET'])
def getNotes(request):
notes = Note.objects.all()
serializer = NoteSerializer(notes, many=True)
return Response(serializer.data)
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect(() => {
getNotes();
}, [])
let getNotes = async () => {
let response = await fetch('http://127.0.0.1:8000/api/notes/')
let data = await response.json()
console.log(data)
setNotes(data)
}
return (
<div>
</div>
)
}
export default NotesListPage
You are not calling your function 'getNotes'
The way I would do it, it to fetch your data in the Effect hook and set it in your state hook there.
import React, { useState, useEffect } from 'react'
const NotesListPage = () => {
let [notes, setNotes] = useState([])
useEffect( async () => {
const response = await fetch('http://127.0.0.1:8000/api/notes/')
.then(response => response.json())
setNotes(response)
}, [])
console.log(notes)
return (
<div>
</div>
)
}
export default NotesListPage
*Edit
Cleaner would be to have the fetch in a seperate function doing the same thing and just calling that function in your effect hook (see other answer above*)

fetching random json getting first undefined then result

Beginner on reactjs here, trying to fetch random json, getting the result i want to get, but not the way i want it, for some reason it prints first 'undefined' then after that the result. Why cant i get just the result and without this '?'
my code:
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
});
}, []);
console.log(thumbnail[0]?.thumbnailUrl);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
console.log() inside App() directly will use the initial state of. thumbnail which is the empty, so it will show undefined.
To check the thumbnail, you should use another useEffect with adding a thumbnail dependency.
useEffect(() => {
if (thumbnail.length > 0) {
console.log(thumbnail[0].thumbnailUrl);
}
}, [thumbnail]);
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoaded, setLoaded] = useState(false);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setLoaded(true);
setThumbnail(json);
});
}, []);
useEffect(() => {
if (isLoaded) {
console.log(thumbnail[0]?.thumbnailUrl);
}
}, [thumbnail]);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
While the response of your http does not come, you can simply render a loading component (a text in this example), then when thumbnail state changes, React will re-render your component and update it with the new data.
Just a working example:
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
})
.finally(() => {
setIsLoading(false);
});
}, []);
return (
<div className="App">
<h1>Build</h1>
{isLoading ? (
<h3>Loading...</h3>
) : (
thumbnail.map((item) => {
return <span key={item.id}>{item.title}</span>;
})
)}
</div>
);
}
export default App;

Categories

Resources