I am creating a react app which is using local storage. I am saving and array of objects to local storage.
when I try to save to local storage the data is saving.
and then when I refresh the page the saved data is becoming empty object,
like this [].
if any one knows why its happening please help me
import React, {useEffect, useState} from 'react';
import Addcontact from './Addcontact';
import './App.css';
import Contactlist from './Contactlist';
import { Header } from './Header';
function App() {
const keyy ="contactlist"
const [contacts, setcontacts] = useState([])
const contactshandler = (contact)=> {
console.log(contact)
setcontacts([...contacts, contact])
}
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])
useEffect(() => {
localStorage.setItem(keyy, JSON.stringify(contacts));
}, [contacts])
return (
<div className="ui container">
<Header />
<Addcontact contacts={contacts} contactshandler={contactshandler} />
<Contactlist contacts={contacts} />
</div>
);
}
app component
import React, { useState } from 'react'
function Addcontact({contacts, setcontacts, contactshandler}) {
const [user, setuser] = useState({username:'', email:''})
const addvalue = (e) => {
e.preventDefault();
console.log(user)
contactshandler(user)
setuser({username:'', email:''})
}
return (
<div>
<div className='ui main'>
<h2> Add Contact</h2>
<form className='ui form' onSubmit={addvalue}>
<div className=''>
<label>name</label>
<input name="name" placeholder='name' value={user.username} onChange={(e) => setuser({...user, username : e.target.value })} />
</div>
<div className='feild'>
<label>email</label>
<input email='email' placeholder='email' value={user.email} onChange={(e) => setuser({...user, email: e.target.value})} />
</div>
<button>add</button>
</form>
</div>
</div>
)
}
export default Addcontact
export default App;
add component
this is the value showing when saving after refresh this value becomes empty object
enter image description here
console
enter image description here
You don't need useEffect to read the data. You can initially read it.
const [contacts, setcontacts] = useState(JSON.parse(localStorage.getItem(keyy)) ?? [])
and remove
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])
Related
I am working with Reactjs and nextjs,Right now i am trying to get input type text value but right now i am not getting any value(name is empty during alert), here is my current code
import dynamic from 'next/dynamic';
import React, { FormEventHandler, useRef } from 'react';
import { useEffect, useState } from "react";
import axios from 'axios';
export default function Testform() {
const [state, setState] = useState({ name: '' });
const [Name, setName] = useState('');
const handleChange = (event:any) => setState({...state, name: event.target.value })
const submitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
event.preventDefault();
const name = Name;
alert('name is '+ name);
}
return (
<form className="forms-sample" onSubmit={submitHandler}>
<div className='flex-dvs'>
<div className="form-group">
<h3>Blog title</h3>
<input type="text"
className="form-control"
id="exampleInputName1"
placeholder="Title"
name="name"
value={state.name}
onChange={handleChange}
/>
</div>
</div>
<div className='save-btn text-right'>
<button className='btn btn-primary mr-2'>Save</button>
</div>
</form>
)
}
You are setting the state variable. So use state.name instead of Name
const name = state.name;
i want to pass a prop from one(App.jsx) component to other component(form.jsx) in state hooks
App.jsx
import React, {useEffect, useState} from 'react';
import Form from './components/Form';
import Table from './components/Table';
import axios from 'axios';
const App = () => {
const [data, setData] = useState({data:[]});
const [editData, setEditData] = useState([]);
const create = (data) => {
axios.post('http://localhost:5000/info',data).then((res) =>{
getAll();
})
}
useEffect(() =>{
getAll();
},[])
const getAll = () =>{
axios.get("http://localhost:5000/info").then((response) =>{
setData({
data:response.data
})
})
}
const update = event =>{
setEditData(data)
console.log(data); // THIS "data" is the prop that i need to pass to Form.jsx component
}
return (
<div>
<div>
<Form myData={create} editForm={editData} />
</div>
<div>
<Table getData={data} edit={update} />
</div>
</div>
);
};
export default App;
i want that "data" value form App.jsx component as props in this Form.jsx component
Form.jsx
import React, {useState} from 'react';
const Form = (props) => {
const [formData, setFormData] = useState({ Name:'', Age:'', City:''});
const infoChange = e => {
const { name,value} = e.target;
setFormData({
...formData,
[name]: value,
})
}
const infoSubmit = e =>{
e.preventDefault();
let data={
Name:formData.Name,
Age:formData.Age,
City:formData.City
}
props.myData(data);
}
const componentWillReceive = (props) => { // i want the props data here
console.log(props.data); // in class component they use componentWillReceiveRrops ,
} // is there any alternative for function based component to receive props?
return (
<div>
<form onSubmit={infoSubmit} autoComplete="off">
<div>
<label>Name:</label>
<input type="text" onChange={infoChange} name="Name" value={formData.Name} placeholder="Enter Name" />
</div>
<div>
<label>City:</label>
<input type="text" onChange={infoChange} name="City" value={formData.City}
placeholder="Enter City" />
</div>
<div>
<label>Age:</label>
<input type="text" onChange={infoChange} name="Age" value={formData.Age} placeholder="Enter Age" />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default Form;
i have commented the area of problem within the code , you can ignore the return () block of code.
Sorry for silly questions but THANKYOU Very Much !!! in advance
Use the following code in Form.jsx, the useEffect will listen the change of props.data and update the value
useEffect(() => {
setFormData(props.data);
},
[props.data]);
For more information, you may check the following answer
https://stackoverflow.com/a/65842783/14674139
I ma creating app to get pokemons, first I save them in a list and after that show them, but I am getting empty card and after that the same pokemn is showing even if I am searching for another one.
Also I am getting distortion view when I use my component
import { useState, useEffect } from "react";
import "./App.css";
import { v4 } from "uuid";
import Button from "./Components/Button";
import Input from "./Components/Input";
import Label from "./Components/Label";
import Card from "./Components/Card";
import axios from "axios";
function App() {
// const [textFromInput, setTextFromInput] = useState("");
const [name, setName] = useState("");
const [nameFromButtonClick, setNameFromButtonClick] = useState("");
const [pokemon, setPokemon] = useState({
name: "",
picture: "",
id: 0,
type1: "",
type2: "",
});
const [list, setList] = useState([]);
const handleChange = (event) => setName(event.target.value);
const handleClick = () => {
setNameFromButtonClick(name);
setList([...list, pokemon]);
};
// const handleClick = () => setList([...list, pokemon]);
useEffect(() => {
axios
.get(`https://pokeapi.co/api/v2/pokemon/${name}/`)
.then((res) => {
console.log(res);
// setPokemon(res.data);
console.log("res.data=>", res.data);
setPokemon({
name: res.data.name,
picture: res.data.sprites.front_default,
id: res.data.id,
type1: res.data.types[0].type.name,
type2: res.data.types[1].type.name,
});
})
.catch((err) => {
console.log(err);
});
}, [nameFromButtonClick]);
return (
<div className="App">
<div>
<h1>Pokémon Effect</h1>
</div>
<div className="centered">
<div className="container">
{list.map((entry) => (
<Card key ={v4()}
name={entry.name}
picture={entry.picture}
id={entry.id}
type1={entry.type1}
type1={entry.type2}
/>
))}
</div>
<div className="dashboard">
<Input className="input" value={name} onChange={handleChange} />
<Button
className="getPokemon"
text="GetPokemon"
onClick={handleClick}
/>
<Label text={name} />
</div>
</div>
</div>
);
}
export default App;
this is my component Card, I don't know how to make it look like when I ma writing directly in app.js
export default function Card(props){
const{name, picture,id,type1,type2}=props
return(
<div className="card">
<div><img src={picture} alt={name} /></div>
<p>n:{id}</p>
<div> name={name}</div>
<div className="pokeType">
<div className="classType">type={type1}</div>
<div className="classType">type={type2}</div>
</div>
</div>
)
}
import '../Search.css';
import React, {setState} from 'react';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faSearch } from '#fortawesome/free-solid-svg-icons'
import PrepodsList from './PrepodsList';
import prepods from "../Data";
const element = <FontAwesomeIcon icon={faSearch} />
const Search = () => {
const [value, setValue] = setState('');
const filteredNames = prepods.filter(prepod => {
return prepod.name.toLowerCase().includes(value.toLowerCase())
})
return(
<div className="search">
<div className="input-container">
<input placeholder="Name" type="text" onChange ={(event) => setState(event.target.value)}></input>
<button onClick={this.addSearch}>{element}</button>
</div>
<div className="wrapper">
{filteredNames.map(prepod => (
<PrepodsList name={prepod.name} key={prepod.id} faculty={prepod.faculty} />
))}
</div>
</div>
)
}
export default Search
This is my Component!
I do not know how to fix this problem.
I don't understand why I don't have my list filtered.
I read a lot of information but still can't solve the problem.
enter image description here
I have a simple form rendering with reactjs and I want to pass a param from the form to complete a route to a test endpoint.
Here is the endpoint: https://jsonplaceholder.typicode.com/comments?postId=1
Here is the component:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios'
import MenuCombo from './menucombo'
const heading = "Enter a price cap here for recommendations"
class App extends Component {
handleSubmit = (e) => {
e.preventDefault()
axios.get('https://jsonplaceholder.typicode.com/comments?postId=PriceCap')
.then(response =>{
console.log("FOUND", response)
})
.catch(err => {
console.log("NOT FOUND",err)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">{heading}</h1>
</header>
<div>
<form onSubmit={this.handleSubmit}>
<label>Enter a price</label>
<input name = 'PriceCap'
type = 'number'
min = '1'
max ='20'/>
<button>Generate Suggestions</button>
</form>
</div>
</div>
);
}
}
export default App;
As you can see I cam passing the form element with the name PriceCap ideally the user would set this to 1 to log the data. And if it is set to any other value than 1 it logs an error. But I can't seem to get the parameter to pass properly.
I feel like this would be easier with POST but I also feel like POST is overkill given that I am only sending one param.
Set a reference to your input by
<input
name = 'PriceCap'
ref = {node => {this.input = node}}
type = 'number'
min = '1'
max ='20'
/>
Then you can access the value in your submit handler by
handleSubmit = event => {
let PriceCap = this.input.value;
axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${PriceCap}`)
.then(...).catch(...)
}
You want something like this:
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
class App extends React.Component {
state = {
val: ""
};
handleSubmit = e => {
e.preventDefault();
axios
.get(
`https://jsonplaceholder.typicode.com/comments?postId=${this.state.val}`
)
.then(response => {
console.log("FOUND", response);
})
.catch(err => {
console.log("NOT FOUND", err);
});
};
render() {
return (
<div className="App">
<div>
<form onSubmit={this.handleSubmit}>
<label>Enter a price</label>
<input
name="PriceCap"
type="number"
min="1"
max="20"
onChange={e => this.setState({ val: e.target.value })}
/>
<button>Generate Suggestions</button>
</form>
</div>
</div>
);
}
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Working example here.
Here, you store the input value in state, and then use that in your get() call.
Notice we added the state, and also an onChange in the input.