I am getting a response saying api token is undefined in React - reactjs

I have written correctly in .env.local file as REACT_APP_API_KEY=myapikeytoken and my key is also correct but I am getting token undefined when I console.log response. This is the website url - https://app.json-generator.com/ from where I generated a fake API.
Below is the code where I am fetching an api.
import React, { useEffect } from "react";
import "./header.css";
const Header = () => {
const getHeaderData = async () => {
const apiKey = process.env.REACT_APP_API_KEY;
const response = await fetch(
`https://api.json-generator.com/templates/jy5YJ7qSuzOt/data?access_token=${apiKey}`
);
console.log(response);
if (response.ok) {
console.log(response);
} else {
console.log("response failed");
}
const data = response.json();
console.log(data);
};
useEffect(() => {
getHeaderData();
}, []);
return (
<>
<div className="dvHeader">
<div className="container-lg">
<div className="row align-items-center pt-1">
<div className="col d-lg-none">
<i className="fa-solid fa-bars"></i>
</div>
<div className="col col-lg-auto text-center text-lg-left">
<img
width={50}
src="https://static.wixstatic.com/media/2c0034_a27b95faba1d432fbddcf6ac4e9683ba~mv2.png"
alt=""
/>
</div>
<div className="dvSlideMenu col-lg-auto px-0 px-lg-3">
<button className="btn btn-black closeBtn d-lg-none">
<i className="fa-solid fa-xmark"></i>
</button>
<ul className="dvMenu">
<li>
Home
</li>
<li>
Shop
</li>
<li>
Login
</li>
<li>
Signup
</li>
</ul>
</div>
<div className="col col-lg-auto ml-lg-auto text-right">
<i className="fa-solid fa-cart-shopping"></i>
</div>
</div>
</div>
</div>
</>
);
};
export default Header;

Fetch is already async and you do not need to await it. I would also suggest that you use fetch like this:
const getHeaderData = async () => {
fetch(`https://api.json-generator.com/templates/jy5YJ7qSuzOt/data?access_token=${process.env.REACT_APP_API_KEY}`)
.then((response) => response.json())
.then((response) => {
// Response is ok, do something
})
.catch((error) => {
// Some error, handle it here
});
}
Read more about it:
https://reactjs.org/docs/faq-ajax.html
https://www.freecodecamp.org/news/fetch-data-react/

I found the issue. The issue was await. I didn't wrote await before response.json().
Code should look like this below:
const getHeaderData = async () => {
const apiKey = process.env.REACT_APP_API_KEY;
const response = await fetch(
`https://api.json-generator.com/templates/jy5YJ7qSuzOt/data?access_token=${apiKey}`
);
console.log(response);
if (response.ok) {
console.log(response);
} else {
console.log("response failed");
}
const data = await response.json(); //added await here
console.log(data);
};

Related

dynamically fetching data from mongoose

I need to fetch data from the MongoDB collection after the user clicks the id properties of the document
[frontend][1]
[1]: https://i.stack.imgur.com/fmW1N.jpg
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
const ViewVehicles = () => {
const [vehicles, setVehicles] = useState(null);
useEffect(() => {
const fetchvehicles = async () => {
const response = await fetch("/headofDeployement/registerVehicle");
const json = await response.json();
if (response.ok) {
setVehicles(json);
}
};
fetchvehicles();
}, []);
return (
<div className="container ">
<div className="row ">
<div className="col justify-content-center align-center">
<h4>Vehicles Registered</h4>
{vehicles &&
vehicles.map((vehicle) => (
<ul key={vehicle._id}>
<a href="" className="text-danger">
{vehicle._id}
</a>
</ul>
))}
</div>
</div>
</div>
);
};
export default ViewVehicles;
I'm not sure if I understand correctly but you should use the Link component you imported from react-router-dom.
For further reading and methodology of how this use case can be handled, check: https://v5.reactrouter.com/web/example/url-params

filter component react either with search or buttons

I have a page that renders a list of dogs from the DogAPI. I don't want to make too many changes in existing code but would like to filter what is currently displayed, was thinking either search box or buttons that show the different breeds. What would be the best approach to do this? I have looked at this article (https://dev.to/salehmubashar/search-bar-in-react-js-545l) but with what I currently have it might cause some things to break, especially the part where I use the ID to link to individual pages.
Here is what I have currently:
import { useState, useEffect } from "react";
import {
Link
} from 'react-router-dom';
import Loading from "./Loading";
export default function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(`https://api.thedogapi.com/v1/breeds`, {
method: "GET", // default GET
headers: {
'Content-Type': 'application/json',
'x-api-key': `${process.env.REACT_APP_API_KEY}`,
},
})
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then((actualData) => {
setData(actualData);
setError(null);
console.log("data", actualData);
})
.catch((err) => {
setError(err.message);
setData(null);
})
.finally(() => {
setLoading(false);
});
}, []);
return <div className="container-fluid">
{loading && <div className="text-center"><Loading /></div>}
{error && (
<div>{`There is a problem fetching the post data - ${error}`}</div>
)}
<ul className="row justify-content-center">
{data &&
data.map(({id,name,image,bred_for,life_span}) => (
<Link to={"/dog/" + id} className="col-md-4 col-sm-6 card my-3 py-3 border-0">
<li key={id}>
<h3>{name}</h3>
<div className="card-img-top text-center">
<img src={image.url} className="photo w-75" />
</div>
<p>{bred_for}</p>
<p>{life_span}</p>
</li>
</Link>
))}
</ul>
</div>;
}
I simplified things down a bit for the sake of example, but this is a little search filter to use as an example to get started. Could hook up the same logic to buttons or preconfigured filter options instead of search input.
import { useEffect, useState } from "react";
export default function App() {
const [data, setData] = useState([]);
const [filtered, setFiltered] = useState([]);
useEffect(() => {
fetch(`https://api.thedogapi.com/v1/breeds`, {
method: "GET", // default GET
headers: {
"Content-Type": "application/json",
"x-api-key": `${process.env.REACT_APP_API_KEY}`
}
})
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then((actualData) => {
setData(actualData);
setFiltered(actualData);
});
}, []);
return (
<div className="container-fluid">
<div>
<input
onChange={(event) => {
const value = event.target.value;
const filtered = data.filter((dog) => dog.name.includes(value));
setFiltered(filtered);
}}
/>
</div>
<ul className="row justify-content-center">
{filtered.map(({ id, name, image, bred_for, life_span }) => (
<a
to={"/dog/" + id}
className="col-md-4 col-sm-6 card my-3 py-3 border-0"
key={name}
>
<li key={id}>
<h3>{name}</h3>
<div className="card-img-top text-center">
<img src={image.url} className="photo w-75" height="48px" />
</div>
<p>{bred_for}</p>
<p>{life_span}</p>
</li>
</a>
))}
</ul>
</div>
);
}

Problem in implementing file Upload in Reactjs

I am Implementing a file upload feature to get resume of job applicants in my Reactjs form.
Now whenever I click on Upload everything works fine but while the file is uploading browser throws an error.
Here is my fileUpload.js.
import React, { useState, useRef } from "react";
import axios, { CancelToken, isCancel } from "axios";
import { LinearProgressWithLabel } from "./ProgressBar";
const FileUpload = () => {
const [uploadPercentage, setUploadPercentage] = useState(0);
const cancelFileUpload = useRef(null);
const uploadFile = ({ target: { files } }) => {
let data = new FormData();
data.append("file", files[0]);
const options = {
onUploadProgress: progressEvent => {
const { loaded, total } = progressEvent;
let percent = Math.floor((loaded * 100) / total);
if (percent < 100) {
setUploadPercentage(percent);
}
},
cancelToken: new CancelToken(
cancel => (cancelFileUpload.current = cancel)
)
};
const BASE_URL = "https://api.quantel.in"
axios
.post(
`${BASE_URL}/api/v1/jobs/resume`,
data,
options
)
.then(res => {
console.log(res);
setUploadPercentage(100);
setTimeout(() => {
setUploadPercentage(0);
}, 1000);
})
.catch(err => {
console.log(err);
if (isCancel(err)) {
alert(err.message);
}
setUploadPercentage(0);
});
};
const cancelUpload = () => {
if (cancelFileUpload.current)
cancelFileUpload.current("User has canceled the file upload.");
};
return (
<>
<p>
<input
type="file"
className="form-control-file"
onChange={uploadFile}
/>
</p>
{uploadPercentage > 0 && (
<div className="row mt-3">
<div className="col pt-1">
<LinearProgressWithLabel value={uploadPercentage} />
</div>
<div className="col-auto">
<span
className="text-primary cursor-pointer"
onClick={() => cancelUpload()}
>
Cancel
</span>
</div>
</div>
)}
</>
);
};
export default FileUpload;
When I click on the browse button the browser throws the following error. And I am confused why is it so?
When you check for uploadPercentage > 0 change that to this
{uploadPercentage > 0 ? (
<div className="row mt-3">
<div className="col pt-1">
<LinearProgressWithLabel value={uploadPercentage} />
</div>
<div className="col-auto">
<span
className="text-primary cursor-pointer"
onClick={() => cancelUpload()}
>
Cancel
</span>
</div>
</div>
) : null }
All your code inside { ... } is treated as a function (inside JSX) and in your case when uploadPercentage === 0 it is returning undefined.

React: Parsing error: Unexpected token, expected "("

i am getting Parsing error: Unexpected token, expected "(".
I have no idea where i'm getting this unexpected error. anyways i'm probably new to reactJS. It would be great if anybody could figure out where i'm getting this unexpected error. thank you so much in advance.
./src/components/listing/Search.js :
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick = (event) => {
axios.get("http://localhost:8000/api/car/p_list?search=" + event, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
return (
<React.Fragment>
<section class="product_list section_padding">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="product_sidebar">
<div class="single_sedebar">
<form>
<input type="text" name="search" onChange={handleChange} placeholder="Search keyword"/>
<i class="ti-search" onClick={handleClick}></i>
</form>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="product_list">
<div class="row"> <br/><br/><br/>
{
posts.map((post) => {<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.product_image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>})
}
</div>
</div>
</div>
</div>
</div>
</section>
</React.Fragment>
);
}
I see 2 issues with your snippet.
Firstly, since you are using an arrow function for handleClick, you need to change it to:
const handleClick = (event) => {
axios.get("http://localhost:8000/api/car/p_list?search=" + event, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
Secondly,
{
posts.map((post) => {
return(
<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.product_image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>
)
})
}
As an aside, the ul tag is misused here. You should use a div instead. That should not stop your code from working though but for the sake of knowledge and working in a production environment, it's important you always use the right tags. You can learn more here
you need to change this part
const handleClick = (event) => {
axios.get("http://localhost:8000/api/car/p_list?search=" + event, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
you cannot use the function and arrow function syntax simultaneously!

react hooks : Uncaught TypeError: data.posts.map is not a function

I'm trying to make a list of jokes but it is saying " TypeError: data.posts.map is not a function ".
I used before same code but different API and it was working.
In console it is showing those posts but on app i get error saying that " data.posts.map "
Can anyone help me?
Thanks
This is my code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const PostArea = () => {
const [like, showLike] = useState(false);
const [color, setColor] = useState('#000');
const likePrint = () => {
showLike(!like);
}
const [data, setPost] = useState({ posts: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
console.log({ posts: result.data });
setPost({ posts: result.data });
};
fetchData();
}, []);
return (
<div>
{data.posts && data.posts.map(({ id, setup, delivery, category }) => {
return (
<div key={id} className="post">
<div className="header">
<a>
<img src="https://unsplash.it/40" alt=" title" />
<div>
<span className="detail">Category :{category}</span>
</div>
</a>
</div>
<div className="content">
<p>
{setup}
</p>
<p>
{delivery}
</p>
</div>
<div className="footer">
<ul>
<li>
<a style={{ color: color }} onClick={() => { likePrint(!like); setColor('#2274a5') }}>
<i className="fas fa-heart"></i>
</a>
</li>
<li>
<a>
<i className="fas fa-comment"></i>
</a>
</li>
<li>
<a>
<i className="fas fa-share-alt-square"></i>
</a>
</li>
</ul>
</div>
</div>
);
})}
</div>
);
}
export default PostArea;
Error : Uncaught TypeError: data.posts.map is not a function
I was looking at the response from the https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40, and it seems like it is returning an object, rather an array, which is the expected type of data.post.
I guess you would want to include this object as part of the post array?
const fetchData = async () => {
const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
setPost({ posts: [result.data] });
};

Resources