Different value in browser and in console - javascript

Can someone please explain to me why in this code when I type a character the character that appears in the label tag is different from the character that appears on the console? Is the code correct?
import React, { useState } from "react";
const App = () => {
const [text, settext] = useState("");
const update = (e) => {
settext(e.target.value);
console.log(text);
};
return (
<div>
<input type="text" value={text} onChange={update} />
<label>{text}</label>
</div>
);
};
export default App;

The settext doesn't update the text state instantly. So calling console.log(text) right after it will give interesting results.
What you want to use is useEffect to log out the value of text.
import React, { useState, useEffect } from "react";
const App = () => {
const [text, settext] = useState("");
const update = (e) => {
settext(e.target.value);
};
useEffect(() => console.log(text), [text]);
return (
<div>
<input type="text" value={text} onChange={update} />{" "}
<label> {text} </label>{" "}
</div>
);
};
export default App;

Related

validate a form in the parent component react

I have a two inputs in my child component, I would like to pass the event of the inputs to my parent component. In the parent component I have a function which will handle the submission. I have the two useState in the parent component, just in case I need to use it in the future in other condition to ensure the user is logged in. I am wondering how to achieve this ? or am I taking the wrong approach with having the usestates in my parent component ?
import { useState } from "react";
import Child from './Child'
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
const loginhandler = ()=>{
if (!login && !password){
console.log("alert error")
} else {
console.log('you are logged in')
}
}
return (
<>
<Child/>
</>
);
}
import { useState } from "react";
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
return (
<>
<input
placeholder="Id"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
<input
placeholder="Password"
value={password}
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</>
);
}
you can pass function like this:
const setParentState = (val) => setLogin;
how do you pass this function to the child component:
<Child setParentPassword={setParentState} />
this way you can use the child components variables and use or set it in parent state
Flow should be like this :
import { useState } from "react";
import Child from './Child'
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
const loginhandler = ()=>{
//your logic will goes here
if (!login && !password){
console.log("alert error")
} else {
console.log('you are logged in')
}
}
return (
<>
<Child
loginhandler={loginhandler}
setLogin={setLogin}
setPassword={setPassword}
/>
</>
);
}
import { useState } from "react";
import "./styles.css";
export default function Child({loginhandler, setLogin, setPassword}) {
return (
<>
<input
placeholder="Id"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
<input
placeholder="Password"
value={password}
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={loginhandler}>LOGIN</button>
</>
);
}

Cannot input into text box or click button in react

I cannot click on my input text box or button at all anymore for some reason. It broke as I was styling the elements. When i first load the page, the autofocus attribute still works but as soon as I try to click the button or re-enter the text box it doesn't work.
import React, { useState } from 'react';
import axios from 'axios';
function Header() {
const [text, setText] = useState("");
function handleChange(event) {
setText(event.target.value);
}
function handleClick() {
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&limit=5&appid=feab629ddad64dc21d6412ebae467d79"
function getCoordinates(url) {
axios.get(url).then((response) => {
const locationLat = response.data[0].lat;
const locationLon = response.data[0].lon;
console.log(locationLat, locationLon);
});
}
getCoordinates(geoCoderURL);
}
return (
<div className="header">
<h1 className="headerTitle">Five Day Forecast</h1>
<input onChange={handleChange} type="text" name="name" autoFocus placeholder="Enter city name here."/>
<button type="submit" onClick={handleClick}>Forecast</button>
</div>
)
}
export default Header;
Check this. Here is the Sandbox Link
import React, { useState } from "react";
import axios from "axios";
function Header() {
const [text, setText] = useState("");
const [locationLat, setlocationLat] = useState("");
const [locationLon, setlocationLon] = useState("");
function handleClick() {
console.log(text);
axios.get(
`https://api.openweathermap.org/geo/1.0/direct?q=${text}&limit=5&appid=feab629ddad64dc21d6412ebae467d79`
)
.then(function (response) {
setlocationLat(response.data[0].lat);
setlocationLon(response.data[0].lon);
})
.catch(function (error) {
console.log(error);
});
}
function handleInput(e) {
setText(e.target.value);
}
return (
<div className="header">
<h1 className="headerTitle">Five Day Forecast</h1>
<input
onChange={handleInput}
type="text"
name="name"
autoFocus
placeholder="Enter city name here."
/>
<button onClick={handleClick}>Forecast</button>
<p>{locationLat}</p>
<p>{locationLon}</p>
</div>
);
}
export default Header;
Revoke the API Key or APP ID, Don't post it publically

How to debounce a function?

I am trying to set a timer for onChange but I don't understand why it doesn't work. I tried several methods, but none of them worked. What can I change to make it work?
import React, {useState} from 'react'
import { debounce } from "lodash";
const Search = ({getQuery}) => {
const [text, setText] = useState('')
const onChange = (q) => {
setText(q)
getQuery(q)
}
const handleDebounce = () => {
debounce(onChange, 3000);
};
return (
<section className='search'>
<form>
<input
type='text'
className='form-control'
placeholder='Search characters'
value={text}
onChange={(e) => handleDebounce( onChange(e.target.value), 3000)}
autoFocus
/>
</form>
</section>
)}
export default Search
removce handleDebounce completely and call your own onChange at the input onChange
onChange={onChange}
then adjust your onChange implementation as:
const onChange = (e) => {
const query = e.target.value;
setText(query);
debounce(() => getQuery(query), 3000);
}

Share State between two components [ Hooks ]

I need help, is there any possible way to send the useEffect submittedInput from search.js to AllThemeContext.js to use it as value of Provider ?
Both are in two different folders [adjacent components]
/Search Js/
/*Import*/
import React, { useState } from "react";
import "./Search.scss";
/*Component*/
const Search = () => {
/************************************************************************************************/
/***************************************************The Logic Area/
/****************************************************************/
/*The state used*/
const [input, setInput] = useState("");
const [submittedInput, setSubmittedInput] = useState("");
/*Functions used*/
// onFormSubmit
const onFormSubmit = (e) => {
e.preventDefault();
setInput("");
};
/************************************************************************************************/
/*************************************************** The Return Area/
/****************************************************************/
return (
<>
<div className="Search">
<form onSubmit={onFormSubmit} className="Search__form">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
type="text"
placeholder=" Title, companies, expertise, or benefits"
style={{ fontFamily: "Poppins, FontAwesome" }}
></input>
<button onClick={() => setSubmittedInput(input)}>Search</button>
</form>
</div>
</>
);
};
/************************************************************************************************/
/***************************************************The Component End Area/
/****************************************************************/
export default Search;
/All Theme context/
import React, { createContext, useState } from "react";
export const AllContext = createContext();
/*Provider*/
const AllContextProvider = (props) => {
const [input, setInput] = useState();
const [numbs, setNumbs] = useState(1);
return (
<AllContext.Provider value={{ input, numbs }}>
{props.children}
</AllContext.Provider>
);
};
export default AllContextProvider;

React not displaying text upon form submission

I'm trying to take input and then display it once the form is submitted but it is not being displayed.
I first use a hook to get the text inside the input field. Once the button is pressed I run a function that uses another hook and sets its value to the text in the input field. This is then put inside the render.
The problem I'm having is that as soon as I submit the form, the screen goes blank.
I have attached my code below.
import React from "react";
import { useState } from "react";
const App = () => {
const [Text, setText] = useState('');
const [Input, setInput] = useState('');
const showInp = (e) => {
e.preventDefault();
setInput(Text);
};
return(
<div className="Main">
<p>
The following cryptocurrencies are available: Bitcoin(BTC).
</p>
<form onSubmit={showInp}>
<label htmlFor="CurrencyName">Currency Name: </label>
<input type="text" className="CurrencyName" value={Text} onChange={(e) => setText(e.target.value)} />
<button style={{marginLeft:"5px"}} type="submit">Submit</button>
</form>
{Input !== '' &&(
{Input}
)}
</div>
)
}
export default App;
Any help would be appreciated.
You have syntax error while rendering Input value. instead of Input value you are rending an object which has Input key and its values is Input, and react can not render objects, it will throw an error.
import React from 'react';
import { useState } from 'react';
const App = () => {
const [Text, setText] = useState('');
const [Input, setInput] = useState('');
const showInp = e => {
e.preventDefault();
setInput(Text);
};
return (
<div className="Main">
<p>The following cryptocurrencies are available: Bitcoin(BTC).</p>
<form onSubmit={showInp}>
<label htmlFor="CurrencyName">Currency Name: </label>
<input
type="text"
className="CurrencyName"
value={Text}
onChange={e => setText(e.target.value)}
/>
<button style={{ marginLeft: '5px' }} type="submit">
Submit
</button>
</form>
{/* Below line had error */}
{Input !== '' && Input}
</div>
);
};
export default App;

Categories