NodeJS Axios - Cant show my get request on screen - node.js

On this case I am trying to show the "_id".
I made the code based on this video.
But by just looking at his API I can see that his data is little different, how can I adapt it to work with my API
import "./App.css";
import axios from "axios";
import { useEffect, useState } from "react";
const App = () => {
const [leitura, setLeitura] = useState([]);
const getLeituraData = async () => {
try {
const data = await axios.get(
"https://estufaarduino.herokuapp.com/sistema/leituras"
);
console.log(data.data);
setLeitura(data.data);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
getLeituraData();
}, []);
return (
<div className="App">
{leitura.map((item) => {
return <p>{item._id}</p>;
})}
</div>
);
};
export default App;

Related

Does axios need extra config to get data from REST API?

I am trying to convert the fetch API to axios with get method.
Prior to do this, I plan to keep using 'async, await'.
And when I replaced the code below:
// before
const fetchPlanets = async () => {
const res = await fetch("http://swapi.dev/api/planets/");
return res.json();
};
// after
const fetchPlanets = async () => {
const res = await axios
.get("http://swapi.dev/api/planets/")
.then((respond) => {
respond.data;
});
};
async can be used when to address the function.
and returned const res as res.json();
Also...axios does not require to res.json as it returned as json type.
That's how I understand this so far. And with fetch API, this work flawlessly.
How the code should be to let axios work as I expected?
// Planets.js
import React from "react";
import { useQuery } from "react-query";
import Planet from "./Planet";
// import axios from "axios";
const fetchPlanets = async () => {
const res = await fetch("http://swapi.dev/api/planets/");
return res.json();
};
const Planets = () => {
const { data, status } = useQuery("planets", fetchPlanets);
console.log(data);
return (
<div>
<h2>Planets</h2>
{status === "loading" && <div>Loading data...</div>}
{status === "error" && <div>Error fetching data!</div>}
{status === "success" && (
<div>
{data.results.map((planet) => (
<Planet key={planet.name} planet={planet} />
))}
</div>
)}
</div>
);
};
export default Planets;
And Planet.js; just in case.
import React from "react";
const Planet = ({ planet }) => {
return (
<div className="card">
<h3>{planet.name}</h3>
<p>Population - {planet.population}</p>
<p>Terrain - {planet.terrain}</p>
</div>
);
};
export default Planet;
There are 2 problems in your axios code.
You should return respond.data.
You should return the whole axios response.
So this would work:
const fetchPlanets = async () => {
return await axios
.get("http://swapi.dev/api/planets/")
.then((respond) => {
return respond.data;
});
};

why i cant get an axios response in react?

so I'm having a problem getting data from my server to my front-end using axios.
as you can see in this picture I'm getting a response for the GET method for users/users.
this is my showUsers function
const showUsers = async (req, res) => {
await User.find({})
.then((user) => {
res.status(200).json(user);
})
.catch((error) => {
res.status(400).send(error);
});
};
this is my axios api export
import axios from "axios";
export default axios.create({
baseUrl: "http://localhost:8080/users",
});
and this is my useEffect
import api from "../api/users";
import { useState, useEffect } from "react";
export const LogIn = (props) => {
const { setIsNewMember } = props;
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await api.get("/users");
setUsers(response.data);
} catch (err) {
if (err.response) {
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else {
console.log(`Error: ${err.message}`);
}
}
};
fetchUsers();
}, []);
I'm getting this error on the frontend
so although I'm getting it from the postman and other services I'm not getting it on the front.
any idea why is that happening?

CURRENT_USER null, TypeError: Cannot read properties of null

I am facing an issue my user is always showing null in the backend, I don't know why.
I am following an Udemy course my tutor is saying middleware is responsible for user identification. but the problem is I typed the same code as my tutor is typing but his codes are working fine mine not.
I am using Axios from the front end to make request.
This my controller ==>
export const currentUser = async (req, res) => {
try {
const user = await User.findById(req._id).select("-password").exec();
console.log("CURRENT_USER", user); return res.json({ ok: true });
} catch (err) {
console.log(err);
}
};
This is my middleware ==>
import { expressjwt } from "express-jwt";
export const requireSignIn = expressjwt({ getToken: (req, res) => req.cookies.token, secret: process.env.JWT_SECRET, algorithms: ["HS256"], }) ;
This my front end code where I have been making request ===>
import { useEffect, useState, useContext } from "react";
import axios from "axios";
import { useRouter } from "next/router";
import { SyncOutlined } from "#ant-design/icons";
import UserNav from "../nav/userNav";
import { Context } from "../../context";
const UserRoutes = ({ children }) => {
const { state: { user } } = useContext(Context);
// state
const [ok, setOk] = useState(false);
// router
const router = useRouter();
useEffect(() => {
fetchUser();
}, []);
const fetchUser = async () => {
try {
const { data } = await axios.get("/api/current-user");
console.log(data);
if (data.ok) setOk(true);
} catch (err) {
console.log(err);
setOk(false);
router.push("/login");
}
};
return (
<>
{!ok ? (
<SyncOutlined spin className="d-flex justify-content-center display-1 text-primary p-5" />
) : (
<div className="UserNavSec">
<div className="UserNavCol1">
<div className="UserNavCont"><UserNav/></div
</div>
<div className="UserNavCol2"> {children} </div
</div>
)}
</>
);
};
export default UserRoutes;

How to update value in client site using mongodb?

I am using React in front-end and Node and MongoDB in Back-end. I have created a custom hook from where I am loading the data. The following is the custom hook
import { useEffect, useState } from "react";
const useItems = (id) => {
const [item, setItem] = useState([]);
useEffect(() => {
fetch(`http://localhost:5000/inventory/${id}`)
.then((res) => res.json())
.then((data) => setItem(data));
}, [id]);
return [item];
};
export default useItems;
And this is the component where I am calling the custom hook to load the data.
import React, { useEffect, useState } from "react";
import "./Inventory.css";
import { useParams } from "react-router-dom";
import useItems from "../../hooks/useItems";
const Inventory = () => {
const { id } = useParams();
const [item] = useItems(id);
const quantityDecrease = (newQuantity) => {
let quantity = parseInt(newQuantity) - 1;
const updateQuantity = { quantity };
const url = `http://localhost:5000/inventory/${id}`;
fetch(url, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(updateQuantity),
})
.then((res) => res.json())
.then((data) => {
console.log("success", data);
alert("saved");
});
};
return (
<div>
<div className="col-lg-6">
<p className="inventory-textbox">
<strong>Quantity :</strong> {item.quantity}
</p>
</div>
<button onClick={() => quantityDecrease(item.quantity)}>
Delivered
</button>
</div>
);
};
export default Inventory;
Whenever the Delivered button is clicked the quantityDecrease function is executed and the quantity of the item is decreased by one. Now, my database is working fine. I am being able to update both client and server site but I have to reload the page in order to see the change in the ui. Is there a way I do not have to reload to see the change?
try using the item data as useEffect dependency. it may solve your problem.

window.stripe is not a function

I am trying to create a stripe checkout project but was stuck when I found that the loadStripe promise was not working fine and I have to change the code window.stripe but this is also not working .
Her is my react code :
import React, { useEffect, useRef } from "react";
import { isAuth } from "../helpers/auth";
import { useNavigate } from "react-router-dom";
import styles from "./Pricing.module.scss";
import ScriptTag from "react-script-tag";
const Stripe = require('stripe')
const stripe = window.Stripe('pk_8734579834958')
export const Pricing = () => {
const buttonValue = useRef();
const navigate = useNavigate();
const setBtnValue = (e) => {
buttonValue.current = e.target.value;
};
const checkoutHandler = async (e) => {
const btnValue = buttonValue.current;
console.log(btnValue);
fetch("http://localhost:5000/api/checkout", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
btnValue,
}),
})
.then((result) => result.json())
.then(({ sessionID }) => stripe.redirectToCheckout({ sessionID }))
.then((result) => {
console.log(result.error.message);
});
};
return (
<div>
<ScriptTag
isHydrating={true}
type="text/javascript"
src="https://js.stripe.com/v3/"
/>
<form onSubmit = {checkoutHandler}>
<button
value= 'price_bdsahfbadshb'
type="submit"
className="btn"
name="product"
onClick={setBtnValue}
>
Upgrade Now
</button>
</div>
)
}
Here is my backend code :
router.post('/checkout' , async(req,res) => {
const product = req.body;
console.log(product);
}
As you want to redirect, just try adding <script src="https://js.stripe.com/v3/"></script> into index.html (if not added) so you will able to use window.Stripe.
and remove line const Stripe = require('stripe')
if you want more clarification, go through its official documentation.

Resources