Error handling in React - undefined errors - javascript

I have this code:
import "./styles.css";
import "mvp.css";
import { useState } from "react";
import axios from "axios";
function Books() {
const [book, setBook] = useState("");
const [result, setResult] = useState([]);
const [apiKey, setApiKey] = useState(
""
);
function handleChange(event) {
const book = event.target.value;
setBook(book);
}
function handleSubmit(event) {
event.preventDefault();
axios
.get(
"https://www.googleapis.com/books/v1/volumes?q=" +
book +
"&key=" +
apiKey +
"&maxResults=20"
)
.then((data) => {
setResult(data.data.items);
})
.catch((error) => {
if (error.response) {
alert("No results found.");
} else if (error.request) {
alert("No results found.");
} else if (error.message) {
alert("No results found.");
}
});
}
return (
<div className="App">
<h1>Search For A Book</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<input
type="text"
onChange={handleChange}
className="input"
placeholder="Search..."
/>
<button type="submit">Go!</button>
</div>
</form>
{result.map((book) => (
<a target="_blank" href={book.volumeInfo.previewLink}>
<img src={book.volumeInfo.imageLinks.thumbnail} alt={book.title} />
</a>
))}
</div>
);
}
export default function App() {
return <Books />;
}
And I am trying to do some error handling, and I get my alert messages as expected, however after I click off the alert box I get redirected to a typeerror that says:
book.volumeInfo.imageLinks is undefined
I am trying to suppress this and just go back to the default screen, but I am not sure how to accomplish this.

Related

react-hook-form: Update form data

In my project using react-hook-form to update and create details. There is an issue in the update form, the values are not updating properly, and the code
countryupdate.tsx
import React from 'react'
import { useQuery } from 'react-query'
import { useParams } from 'react-router-dom'
import { useCountryUpdate } from '../api/useCountryUpdate'
import { getDetails, useDetails } from '../api/useDetails'
import { CountryCreateUpdateForm } from '../forms/createupdateForm'
interface data{
id: string,
name: string
}
export const CountryUpdatepage = () => {
const { dataId }: any = useParams()
const { data, isLoading, isError } = useQuery(['details', dataId], () => getDetails(dataId), {
enabled: !!dataId,
});
const { mutateAsync } = useCountryUpdate();
const onFormSubmit = async() =>{
console.log("mutate", {...data})
await mutateAsync({...data, dataId})
}
return (
<div>
<h3>Update Details</h3>
<CountryCreateUpdateForm defaultValues={data} onFormSubmit={onFormSubmit} isLoading={undefined}/>
</div>
)
}
Here, when console the value inside onFormSubmit, it shows the same data in the previous state
createupdateform.tsx
import { useState } from "react"
import { useCountryCreate } from "../api/usecountrycreate"
import { useForm } from "react-hook-form"
export const CountryCreateUpdateForm = ({ defaultValues, onFormSubmit, isLoading }: any) => {
// console.log("name", defaultValues.data.name)
const { register, handleSubmit } = useForm({ defaultValues:defaultValues?.data });
const onSubmit = handleSubmit((data) => {
onFormSubmit(data)
})
return (
<form onSubmit={onSubmit}>
<div>
<label>Name</label>
<input {...register('name')} type="text" name="name" />
</div>
<button type="submit" >submit</button>
</form>
)
}
I am a beginner in react typescript, Please give me suggestions to solve this problem.
in countryupdate.tsx
the data is undefined at the beggining, so defaultValue of form is not updated after that;
it should help:
return (
<div>
<h3>Update Details</h3>
{data?.data && <CountryCreateUpdateForm defaultValues={data} onFormSubmit={onFormSubmit} isLoading={undefined}/>
}
</div>
)

FirebaseError: Firebase: Error (auth/user-token-expired) [duplicate]

This question already has an answer here:
firebase: admin.auth().updateUser() causes auth/user-token-expired
(1 answer)
Closed 8 months ago.
I have created a new form after creating a user with phone number authentication(in firebase), But an error keeps on coming after submitting FirebaseError: Firebase: Error (auth/user-token-expired)
The Error is Comming in this code
//This Component is used to store the Name ,Phone Number Of new User Which have Registered in SignUp With Number
import "./Auth.scss";
import React, { useState } from "react";
import { updateProfile, updateEmail } from "firebase/auth";
import { auth } from "../../firebase/config";
import { useNavigate, useLocation } from "react-router";
import usePhoneSignUp from "../../hooks/usePhoneSignUp";
import { update } from "lodash";
const SaveUserDetails = () => {
//code to extract userType after navigating from SignUpWithNumber page
const { state } = useLocation();
const userType = state.userType;
console.log(userType);
// .......
const {
signUp,
error: signupError,
isPending: signupIsPending,
} = usePhoneSignUp();
const [name, setname] = useState();
const [email, setemail] = useState();
const navigate = useNavigate();
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
switch (name) {
case "displayname":
setname(value);
break;
case "email":
setemail(value);
break;
default:
break;
}
};
const updateEmailUser = () => {
updateEmail(auth.currentUser, email)
.then(() => {
// Email updated!
// ...
console.log("email Updated");
})
.catch((error) => {
// An error occurred
console.log("email Updated");
// ...
console.log(error);
});
};
const updateUserProfile = () => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
};
const handleSubmit = () => {
// updateEmailUser();
updateUserProfile();
signUp(name, userType, email);
let path =
userType === "salonOwner" ? "/addBuisnessDetails" : "/salonsNearby";
if (signupError) {
console.log(signupError.message);
}
return navigate(path, { replace: true });
};
//query function for saloon
return (
<>
<div className="form-wrapper ">
<div id="register-form">
<p className="login-title register-title">Complete Your Profile</p>
<div className="login-hr" />
<form onSubmit={handleSubmit}>
<div className="form-group login-sj">
<label htmlFor="exampleInputName1">Name:</label>
<input
type="text"
className="form-control"
id="exampleInputName1"
aria-describedby="emailHelp"
placeholder="Your Name"
name="displayname"
onChange={handleChange}
/>
</div>
<div className="form-group login-sj">
<label htmlFor="exampleInputEmail2">Email address</label>
<input
type="email"
className="form-control"
id="exampleInputEmail2"
aria-describedby="emailHelp"
placeholder="Enter email"
name="email"
onChange={handleChange}
/>
</div>
{/* <div className="form-group login-sj">
<label htmlFor="exampleInputPassword1"></label>
<input
type="password"
className="form-control"
id="exampleInputPassword2"
placeholder="Password"
value={userPassword}
onChange={(e) => setUserPassword(e.target.value)}
/>
</div> */}
{signupIsPending ? (
<>
<button
type="submit"
className="btn-auth-sj btn btn-primary"
disabled
>
Save Details
</button>
</>
) : (
<>
<button type="submit" className="btn-auth-sj btn btn-primary">
Save Details
</button>
</>
)}
</form>
</div>
</div>
</>
);
};
export default SaveUserDetails;
The part where error is Comming
.catch((error) => {
console.log(error + "In update profile");
});
Due to this my displayName Is not getting saved and after submitting user is getting logged out automatically.
I also asked this question previously and implemented it as answered Is their any function signupwithphonenumber in firebase just like signupwithemailandpassword? (for web) I want to make user register with his creds
Thanks In advance
Okay So the problem got resolved gust by wrapping updateProfile function(one provided by firebase) into
auth.currentUser.reload().then(() => { /* update profile function here */ })
Or In my case :-
const updateUserProfile = () => {
auth.currentUser.reload().then(() => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
});
};

Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null when calling set function

I'm trying to set up a user login system using the userContext and localSotrage of the browser.
I have a first file that includes my provider and my context:
Auth.jsx
import { hasAuthenticated } from '../services/AuthAPI';
export const AuthContext = createContext()
const AuthProvider = ({children}) => {
const [auth, setAuth] = useState(hasAuthenticated());
const value = useMemo(() => ({auth, setAuth}, [auth, setAuth]));
return (
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
)
}
export default AuthProvider
export const AuthState = () => {
return useContext(AuthContext)
}
I also have a page that allows to manage elements of the LocalStorage and to know if a user is already connected (it for now hardcoded):
AuthAPI.jsx
export function hasAuthenticated() {
const token = getItem('sessionToken');
const result = token ? tokenIsValid(token) : false;
if (false === result) {
removeItem('sessionToken');
}
return result;
}
export function login(credentials) {
addItem('sessionToken', 'tokenSample');
return true;
};
export function logout() {
removeItem('sessionToken');
}
function tokenIsValid(token) {
// const { exp: expiration } = jwtDecode(token);
// if (expiration * 1000 > new Date().getTime()) {
// return true;
// }
return true;
}
And finally I have my connection page which must update the auth variable using the context:
Login.jsx
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/Auth';
import { login } from '../services/AuthAPI';
const Login = () => {
const navigate = useNavigate();
const {auth, setAuth} = useContext(AuthContext);
const [user, setUser] = useState({
username: "",
password: ""
})
const handleChange = ({ currentTarget }) => {
const { name, value } = currentTarget;
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault();
try {
const response = await login(user);
setAuth(response);
navigate('news', { replace: true });
console.log('oui');
} catch (e) {
console.error(e);
}
}
useEffect(() => {
if (auth) {
navigate('news', { replace: true });
}
}, [navigate, auth]);
return (
<div className="container border rounder mt-5 p-3 bg-light">
<form className="form-profile" onSubmit={setAuth(true)} >
<fieldset>
<legend>Se connecter</legend>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="text"
name="username"
className="form-control"
id="email"
placeholder="mail#mail.fr"
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
className="form-control"
id="password"
placeholder="Password"
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Se connecter
</button>
</fieldset>
</form>
</div>
);
};
export default Login;
But React returns this error:
Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null site:stackoverflow.com at line setAuth(response); from Login.jsx
Do you have any idea ?

i want to make hacknews userinfo react modal

i don't know how can i print user info react modal
this is my code
import React from "react";
import axios from "axios";
import { useEffect, useState } from "react";
import { Show, User } from "../api";
import UseUser from "../scroll/userInfo";
function ShowContents() {
const [storyIds, setStoryIds] = useState([]);
const [visible, setVisible] = useState(false);
const [getUser, setGetUser] = useState([]);
useEffect(() => {
Show().then((res) => {
this.res = res.data.slice(0, 10);
this.res.forEach(async (ele) => {
await axios
.get("https://hacker-news.firebaseio.com/v0/item/" + ele + ".json")
.then((res) => {
if (Array.isArray(this.res) && this.res.length === 0) {
return;
} else {
setStoryIds((value) => [
...value,
{
id: res.data.id,
title: res.data.title,
url: res.data.url,
user: res.data.by,
score: res.data.score
}
]);
}
});
});
});
}, []);
const menu = storyIds;
const menuList = menu.map((m, i) => (
<div className="box_show" key={i}>
<div className="flex">
<p className="numbers">{i + 1}</p>
<a href={m.url} className="titleFont">
{m.title}
</a>
<a href={m.url}>
<img src={`/assets/back.svg`} alt="" className="imgLink" />
</a>
</div>
<br />
<button
className="userShow"
onClick={() => {
setVisible(!visible);
}}
>
<div className="userNameShow">{m.user}</div>
</button>
</div>
));
return (
<>
{menuList}
{visible && (
<div className="modal-container" id="modal">
<div className="modal">
<div className="modal-top flex">
<p>User Info</p>
<button
className="close-btn"
onClick={() => {
setVisible(!visible);
}}
>
<img src={`/assets/close_black.svg`} alt="" />
</button>
</div>
<UseUser />
</div>
</div>
)}
</>
);
}
export default ShowContents;
The code above is my show partial code.
this is my UserInfo code
import { useState, useEffect } from "react";
import { getUser } from "../api";
const UseUser = (id) => {
// const [user, setUser] = useState({});
// useEffect(() => {
// getUser(id).then((user) => setUser(user));
// }, [id]);
return (
<>
<div className="user-detail flex">
<div className="user-profile"></div>
<div className="user-detail-info">
<p className="modal-user">user : </p>
<p className="modal-created">created : </p>
<p className="modal-karma">karma : </p>
</div>
</div>
<p className="about">about:</p>
<p className="email">Twitter:</p>);
</>
);
};
export default UseUser;
import axios from "axios";
const BASE_URL = "https://hacker-news.firebaseio.com/v0/";
export const storyUrl = `${BASE_URL}item/`;
function News() {
return axios.get(`${BASE_URL}newstories.json`);
}
function Jobs() {
return axios.get(`${BASE_URL}jobstories.json`);
}
function Top_API() {
return axios.get(`${BASE_URL}topstories.json`);
}
function Ask() {
return axios.get(`${BASE_URL}askstories.json`);
}
function Show() {
return axios.get(`${BASE_URL}showstories.json`);
}
function User() {
return axios.get(`${BASE_URL}user`);
}
export { News, Jobs, Top_API, Ask, Show, BASE_URL, User };
this is my api code
When you click the user button in the show part, I want to get information about the user. It's too difficult for me right now.
I tried to implement it using use Effect, but I don't know how to send information about the user when I press the button.
I need help.

Login page issues while using react js and Django api

I am creating a simple login page using react js and Django api. I am able to login but unable to go to my dashboard as it is throwing error like "Unhandled Rejection (TypeError): Cannot read property 'status' of undefined"
I am using Visual Studio Code
The full code is as below:
Login.js
import React, { useState } from 'react';
import axios from 'axios';
import { setUserSession } from './Utils/Common';
function Login(props) {
const [loading, setLoading] = useState(false);
const username = useFormInput('');
const password = useFormInput('');
const [error, setError] = useState(null);
// handle button click of login form
const handleLogin = () => {
setError(null);
setLoading(true);
axios.post('http://localhost:8000/account/user/signin', { mobile_number: username.value,
password: password.value }).then(response => {
setLoading(false);
setUserSession(response.data.token, response.data.user);
props.history.push('/dashboard');
}).catch(error => {
setLoading(false);
if (error.response.status === undefined) setError(error.response.data.message);
else setError("Something went wrong. Please try again later.");
});
}
return (
<div>
Login<br /><br />
<div>
Username<br />
<input type="text" {...username} autoComplete="new-password" />
</div>
<div style={{ marginTop: 10 }}>
Password<br />
<input type="password" {...password} autoComplete="new-password" />
</div>
{error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
<input type="button" value={loading ? 'Loading...' : 'Login'} onClick={handleLogin}
disabled={loading} /><br />
</div>
);
}
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
}
}
export default Login;
Dashboard.js
import React from 'react';
import { getUser, removeUserSession } from './Utils/Common';
function Dashboard(props) {
const user = getUser();
//handle click event of logout button
const handleLogout = () => {
removeUserSession();
props.history.push('/login');
}
return (
<div>
Welcome {user.name}!<br /><br />
<input type="button" onClick={handleLogout} value="Logout" />
</div>
);
}
export default Dashboard;

Categories

Resources