how to fetch data according to slug in ReactJS? - javascript

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.

Related

How to get item.docId so that i can get url for pdf in firestore

i'm trying to implement pdf viewer from url stored in firestore in react js
how i can get item.docId in setPdfUrls please help me out i'm new to react js and web development
Where I'm stuck is that I don't understand how to do it please help
How to get item.docId so that i can get url for pdf in firestore
`
import React, { useState, useEffect, useContext } from "react";
import { Card, Header, Player } from "../components";
import * as ROUTES from "../constants/routes";
import { FirebaseContext } from "../context/firebase";
import { ref, getDownloadURL } from "firebase/storage";
import { storage } from "../lib/firebase.prod";
import { SelectProfileContainer } from "./profiles";
import { FooterContainer } from "./footer";
export function BrowseContainer({ slides }) {
var [pdfUrls, setPdfUrls] = useState([]);
const [resume, setResume]=useState(null);
useEffect(()=>{
getDownloadURL(ref(storage, 'Resume.pdf')).then((url)=>{
setResume(url);
})
},[]);
const [category, setCategory] = useState("articles");
const [profile, setProfile] = useState({});
const [loading, setLoading] = useState(true);
const [slideRows, setSlideRows] = useState([]);
const { firebase } = useContext(FirebaseContext);
const user = firebase.auth().currentUser || {};
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 3000);
}, [profile.displayName]);
useEffect(() => {
setSlideRows(slides[category]);
}, [slides, category]);
return profile.displayName ? (
<>
<Card.Group>
{slideRows.map((slideItem) => (
<Card key={`${category}-${slideItem.title.toLowerCase()}`}>
<Card.Title>{slideItem.title}</Card.Title>
<Card.Entities>
{slideItem.data.map((item) => (
<Card.Item key={item.docId} item={item}>
<Card.Meta>
<Card.SubTitle>{item.title}</Card.SubTitle>
<br/>
<br/>
</Card.Meta>
<Card.Image
src={item.image} alt={item.title}/>
</Card.Item>
))}
</Card.Entities>
<Card.Feature category={category}>
<Player>
<Player.Button />
<Player.Video src={resume} />
</Player>
</Card.Feature>
</Card>
))}
</Card.Group>
<FooterContainer />
</>
) : (
<SelectProfileContainer user={user} setProfile={setProfile} />
);
}
`

How to make a search box working properly on react js

I am a beginner and I am learning React JS. I am doing a basic project in React. I have a search box. When I search for something my page will show search related content.
Here I used includes() to make my search workable. But it is not working.
I have indicated the line of setting a new array of dogs at line 40.
Pleae have a look to my code.
Here is my codes:
Home.jsx
import React, { useState, useEffect } from 'react';
import Dogs from './components/Dogs/Dogs';
import Search from './components/search/Search';
const Home = () => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [value, setValue] = useState('');
const [search, setSearch] = useState('');
const [dogs, setDogs] = useState([]);
useEffect(() => {
fetch('https://api.thedogapi.com/v1/breeds', {
headers: {
Authorization: '4139956d-7014-4fa8-b295-8e361418c807',
},
})
.then(response => response.json())
.then(
data => {
setIsLoaded(true);
setDogs(data);
},
error => {
setIsLoaded(true);
setError(error);
}
);
}, []);
const handleChange = event => {
setValue(event.target.value);
};
const handleSearch = () => {
setSearch(value);
setValue('');
};
// This is the function to making a new array of dogs of searched name
useEffect(() => {
const newDogList = dogs.filter(dog => {
if (dog.name.includes(search)) dog
});
setDogs(newDogList);
}, [search]);
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="container">
<Search
value={value}
handleChange={handleChange}
handleSearch={handleSearch}
/>
<Dogs dogs={dogs} />
</div>
);
}
};
export default Home;
How can I make it workable?

useFetch custom hook not working properly

I am working on react website.
I have created one custom data fetching hook 'usePostFetch' as follows:
import React, { useState, useEffect } from "react";
//axios
import axios from "axios";
const usePostFetch = () => {
const [postData, setPostData] = useState([]);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const getData = async () => {
setIsLoading(true);
try {
const res = await axios.get("http://localhost:8000/Sell");
const data = await res.data;
setPostData(data);
setIsLoading(false);
} catch (error) {
console.log("Error from fetch: " + error);
setError(error.message);
setIsLoading(false);
}
};
getData();
}, []);
const values = [
...new Set(
postData.map((post) => {
return post.productType;
})
),
];
return { postData, values, error, isLoading };
};
export default usePostFetch;
I have a product page that renders when I click any of the links on the home page with a link "/product/:productId".productId is the id of clicked link product.
Product Page:
import React, { useEffect, useState } from "react";
//react router dom
import { useParams } from "react-router";
//Hooks
import usePostFetch from "../../Hooks/usePostFetch";
//styles
import { Wrapper, Info, Discription } from "./Product.styles";
//Server
const Server = "http://localhost:8000";
const Product = () => {
const { productId } = useParams();
const { postData, isLoading, error } = usePostFetch();
const [data, setData] = useState({});
console.log(postData, isLoading, error);
useEffect( () => {
const fetchData = async () => {
var value = await postData.filter((post) => {
return post._id === productId;
});
console.log(value);
setData(value);
};
fetchData();
}, [postData]);
return (
<Wrapper>
<Info>
{isLoading && <h1> Loading.... </h1>}
{error && <p>ERROR </p>}
{console.log(data)}
<img
src={`${Server}/productImages/${data[0].productImage}`}
alt={`${data[0].productName}`}
/>
<div className="data">
<h1>{data[0].productName}</h1>
<h3>{data[0].productPrice}</h3>
</div>
</Info>
</Wrapper>
);
};
export default Product;
But when I go to that link I got data in console like this:
Because of these empty arrays, I got errors like this:
What can I do or what is wrong with my code?
It appears you are reading state that doesn't exist yet. The initial data state is an empty object:
const [data, setData] = useState({});
And on the initial render you are attempting to read from a 0 property, which OFC is undefined still.
data[0] --> OK, undefined
data[0].productName --> NOT OK, throws error trying to access from undefined
You can conditionally render the data content when you know it's populated:
<Wrapper>
<Info>
{isLoading && <h1> Loading.... </h1>}
{error && <p>ERROR </p>}
{console.log(data)}
{data[0] && (
<img
src={`${Server}/productImages/${data[0].productImage}`}
alt={`${data[0].productName}`}
/>
<div className="data">
<h1>{data[0].productName}</h1>
<h3>{data[0].productPrice}</h3>
</div>
)
</Info>
</Wrapper>
Or you can just use the Optional Chaining operator to defend against null/undefined property accesses:
<Wrapper>
<Info>
{isLoading && <h1> Loading.... </h1>}
{error && <p>ERROR </p>}
{console.log(data)}
<img
src={`${Server}/productImages/${data[0]?.productImage}`}
alt={`${data[0]?.productName}`}
/>
<div className="data">
<h1>{data[0]?.productName}</h1>
<h3>{data[0]?.productPrice}</h3>
</div>
</Info>
</Wrapper>
It also seems that you are really expecting data to be an array, so you will want your initial state to maintain a state/type invariant, so it should also be declared as an array.
const [data, setData] = useState([]);

React hook Search on button click not working

I need to get a list of repositories using GitHub API, search has to work on button click and on change selectBox with licences
import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";
import "./App.css";
export const App = () => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false);
const [nameSearch, setNameSearch] = useState("");
const [license, setLicense] = useState({});
const fetchData = useCallback(async () => {
setHasError(false);
setIsLoading(true);
try {
const prevMonth = moment()
.subtract(30, "days")
.format("YYYY-MM-DD");
const licenseKey = (license && license.key) || "";
const response = await axios(
`https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
licenseKey ? `+license:${licenseKey}` : ""
}&sort=stars&order=desc`
);
setData(response.data.items);
} catch (error) {
setHasError(true);
setData([]);
}
setIsLoading(false);
}, [license]);
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<Layout>
<Header>
<Search
handleSearchChange={setNameSearch}
nameSearch={nameSearch}
isLoading={isLoading}
onSearch={fetchData}
/>
<Licenses license={license} handleLicenseChange={setLicense} />
</Header>
<main>
{hasError && <div>Error</div>}
{isLoading ? <Loader /> : <List data={data} />}
</main>
</Layout>
);
};
First of all, I get warning
Compiled with warnings.
./src/components/App/App.js
Line 42:6: React Hook useCallback has a missing dependency: 'nameSearch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
And my search is not working because nameSearch is always empty in the query string.
How to make search work?
Try adding nameSearch to the list of dependencies for useCallback:
const fetchData = useCallback(async () => {
...
}, [license, nameSearch]);
and make sure setNameSearch is actually used inside Search.js so that it will have a value.

How can i passing id which match?

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.

Categories

Resources