Why is my check complete button is not working - reactjs

I wanna make the function that whenever i click on the complete button, the complete state will turn true and there will be a line through in my todo. However, my function is not working and i don't know why? can anyone help me? Thank you so much!
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
// you can use the submit itself, no need for an extra addTodo function
const handleSubmit = (e) => {
e.preventDefault();
setTodos([...todos, { value, id: Date.now() }]);
setValue("");
};
const handleDelete = (id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
/>
<button type="submit">Add</button>
</form>
{todos.map((todo) => (
<div key={todo.id}>
<h3 complete ? "line-through" : "">{todo.value}</h3>
<button onClick={() => handleDelete(todo.id)}>X</button>
<button onClick={()=>setComplete(!complete)}>complete</button>
</div>
))}
</div>
);
}
export default App;
Sandbox link: https://codesandbox.io/s/stoic-mendeleev-6fetl?file=/src/App.js

complete state missing
h3 add style={{ textDecoration: complete ? "line-through" : "" }}
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
const [complete, setComplete] = useState(false);
// you can use the submit itself, no need for an extra addTodo function
const handleSubmit = (e) => {
e.preventDefault();
setTodos([...todos, { value, id: Date.now() }]);
setValue("");
};
const handleDelete = (id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
value={value}
/>
<button type="submit">Add</button>
</form>
{todos.map((todo) => (
<div key={todo.id}>
<h3 style={{ textDecoration: complete ? "line-through" : "" }}>
{todo.value}
</h3>
<button onClick={() => handleDelete(todo.id)}>X</button>
<button onClick={() => setComplete((perv) => !perv)}>complete</button>
</div>
))}
</div>
);
}
export default App;

Try this
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
const [complete, setComplete] = useState({});
// you can use the submit itself, no need for an extra addTodo function
const handleSubmit = (e) => {
e.preventDefault();
const id = Date.now();
setTodos([...todos, { value, id }]);
setComplete({ ...complete, [id]: false });
setValue("");
};
const handleDelete = (id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
};
console.log(complete);
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
value={value}
/>
<button type="submit">Add</button>
</form>
{todos.map((todo) => (
<div key={todo.id}>
<h3 className={complete[todo.id] ? "line-through" : ""}>
{todo.value}
</h3>
<button onClick={() => handleDelete(todo.id)}>X</button>
<button
onClick={() =>
setComplete({ ...complete, [todo.id]: !complete[todo.id] })
}
>
complete
</button>
</div>
))}
</div>
);
}
export default App;
*Note you will need to specify styling for your line-through class to see the strike through

I have updated the codesandbox. you can have look on the codesandbox.
https://codesandbox.io/s/compassionate-frost-8255y

Try below code.
You need to create setComplete menthod.
import React, { useState } from "react";
function App() {
const [value, setValue] = useState("");
const [todos, setTodos] = useState([]);
// you can use the submit itself, no need for an extra addTodo function
const handleSubmit = (e) => {
e.preventDefault();
setTodos([...todos, { value, id: Date.now(), complete: false }]);
setValue("");
};
const handleDelete = (id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
};
const handleComplete = (id) => {
let compTodo = todos.filter((todo) => todo.id === id);
compTodo[0].complete = true;
let allTodo = todos.filter((todo) => todo.id !== id);
setTodos([...allTodo, compTodo[0]]);
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
onChange={(e) => setValue(e.target.value)}
type="text"
placeholder="add todo"
value={value}
/>
<button type="submit">Add</button>
</form>
{todos.map((todo) => {
return (
<div key={todo.id}>
<h3
style={{
textDecoration: todo.complete ? "line-through" : "none"
}}
>
{todo.value}
</h3>
<button onClick={() => handleDelete(todo.id)}>X</button>
<button onClick={() => handleComplete(todo.id)}>complete</button>
</div>
);
})}
</div>
);
}
export default App;

Related

Directus and React data not submitting to API

I'm trying to submit reviews to a directus app but the review is not getting added to the data.
I can retrieve the data but cannot add.
I've checked all permissions and set the directus app to public permissions.
cannot figure out what the problem could be.
can anyone advise what could be wrong?
the api call:
import axios from 'axios';
const url = 'https://pwsbbqhj.directus.app/items/Reviews';
export const readReviews = () => axios.get(url);
export const createReview = (newReview) => axios.post(url, newReview);
the data retrieval :
import React, { useState, useEffect } from 'react';
import * as api from '../../../api';
import { FaStar } from 'react-icons/fa';
const colors = {
orange: '#e42320',
grey: '#a9a9a9',
};
function Ratings() {
const stars = Array(5).fill(0);
const [currentValue, setCurrentValue] = React.useState(0);
const [hoverValue, setHoverValue] = React.useState(undefined);
const handleClick = (value) => {
setCurrentValue(value);
};
const handleMouseOver = (value) => {
setHoverValue(value);
};
const [review, setReview] = useState({});
const [reviews, setReviews] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await api.readReviews();
setReviews(result.data.data);
};
fetchData();
}, []);
const createReview = async (review) => {
try {
const data = await api.createReview({ review });
setReview([...reviews, data.data]);
} catch (error) {
console.log(error);
}
};
let [reviewCount, setreviewCount] = useState([]);
const setCountFxn = (no) => {
setReview(no);
console.log(no);
};
return (
<div className='col-md-12 row-testimonials'>
<div className='reviews-heading pb-5 pt-5'>
<h2>REVIEWS FROM OUR CUSTOMERS</h2>
</div>
<div
className='themesflat-carousel-box has-bullets bullet-circle has-buttons has-arrows clearfix'
data-gap={30}
data-column={3}
data-column2={2}
data-column3={1}
data-auto='false'
>
<div className='owl-carousel owl-theme'>
{reviews.map((review) => (
<div className='themesflat-testimonials style-2 align-center clearfix' key={review.id}>
<div className='testimonial-item'>
<div className='inner'>
<div className='thumb'>
<img src='assets/img/testimonials/customer-1-90x90.jpg' alt='altimage' />
</div>
<blockquote className='text'>
<div className='name-pos clearfix'>
<h6 className='name'>{review.Title}</h6>
<span className='position'></span>
</div>
<p>{review.Body}</p>
<div className='list-star'>
{Array.from({ length: review.Rating }).map((i) => (
<FaStar key={i} size={18} color={colors.orange} />
))}
</div>
<div className='m-2'>
By: <span className='name'>{review.Name}</span>
</div>
</blockquote>
</div>
</div>
</div>
))}
</div>
</div>
<div className='bg-black'>
<form>
<div className='mb-5'>
<h2>RATE OUR SERVICE</h2>
<div className='mt-5 mb-5'>
{stars.map((_, index) => {
return (
<FaStar
key={index}
size={20}
style={{
marginRight: 10,
cursor: 'pointer',
}}
color={(hoverValue || currentValue) > index ? colors.orange : colors.grey}
onClick={() => {
setReview({ ...review, Rating: index + 1 });
}}
onMouseOver={() => handleMouseOver(index + 1)}
/>
);
})}
</div>
<div id='message'></div>
<div>
<input
type='text'
placeholder='Your Name'
required
value={review.Name}
onChange={(e) => setReview({ ...review, Name: e.target.value })}
className='wpcf7-form-control'
/>
</div>
<div>
<input
type='text'
placeholder='Review Title'
required
value={review.Title}
onChange={(e) => setReview({ ...review, Title: e.target.value })}
className='wpcf7-form-control'
/>
</div>
<textarea
placeholder='Your comment'
required
value={review.Body}
onChange={(e) => setReview({ ...review, Body: e.target.value })}
className='wpcf7-form-control'
/>
<button type='submit' className='submit wpcf7-form-control wpcf7-submit' onClick={createReview}>
submit
</button>
</div>
</form>
</div>
<div className='themesflat-spacer clearfix' data-desktop={80} data-mobile={60} data-smobile={60} />
</div>
);
}
export default Ratings;

Updating an array with useState in a form

In the below, I have verified that setNewItem works, however items doesn't get updated so there must be an issue with the function handleSubmit. What is going wrong here?
import "./styles.css";
import React, {useState, useEffect} from 'react';
export default function App() {
const [items, setItems] = useState(['first item']);
const [newItem, setNewItem] = useState("");
const handleSubmit = (event, newItem, items) => {
event.preventDefault();
setItems([ newItem, ...items]);
};
const handleChange = (event) => {
setNewItem(event.target.value);
}
return (
<div>
<form>
<input type="text"
value={newItem}
onChange={handleChange}
/>
<input type="submit"
value="submit"
onSubmit={handleSubmit}
/>
</form>
<ul>
{items.map( (i) => {
return(<li>{i}</li>)
})}
</ul>
</div>
);
}
https://codesandbox.io/s/new?file=/src/App.js:0-797
try this 👇
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [items, setItems] = useState(["first item"]);
const [newItem, setNewItem] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
console.log("here");
setItems([newItem, ...items]);
};
const handleChange = (event) => {
setNewItem(event.target.value);
};
return (
<div>
<form>
<input type="text" value={newItem} onChange={handleChange} />
<input type="button" value="submit" onClick={handleSubmit} />
</form>
<ul>
{items.map((i) => {
return <li>{i}</li>;
})}
</ul>
</div>
);
}
You need to change and try this.
const handleSubmit = (event) => {
event.preventDefault();
setItems([ newItem, ...items]);
};
...
...
...
<input type="submit"
value="submit"
onSubmit={event => handleSubmit(event)}
/>

After editing data, redux cannot read id

i have a problem.
I use a form to edit my data, then when i want to see edited data, i get an ×
TypeError: Cannot read properties of undefined (reading 'id')
Pointing at my
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
Which is used to display data.
After refreshing the site (F5) it works, so i assume that the redux has problem with reading edited data for the first time, altough it do work with adding new data. anyone know what i can do?
My UserEditForm:
const UserEditForm = () => {
let { id } = useParams();
const { user } = useSelector((state) => state.user);
const [state, setState] = useState({
name: "",
birthday: "",
img: "",
});
const [error, setError] = useState("");
console.log(id);
let history = useHistory();
let dispatch = useDispatch();
const { name, birthday, img } = state;
useEffect(() => {
dispatch(getSingleUser(id));
}, []);
useEffect(() => {
if (user) {
setState({ ...user });
}
}, [user]);
const handleInputChange = (e) => {
let { name, value } = e.target;
setState({ ...state, [name]: value });
};
const handleSubmit = (e) => {
dispatch(updateUser(state, id));
history.push("/");
setError("");
};
return (
<div>
<Button
style={{ width: "100px", marginTop: "20px" }}
variant="contained"
color="secondary"
onClick={() => history.push("/")}
>
Go Back
</Button>
<h2>Edit User</h2>
{error && <h3 style={{ color: "red" }}>{error}</h3>}
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
id="standard-basic"
label="Name"
value={name || ""}
name="name"
type="text"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="birthday"
name="birthday"
value={birthday || ""}
type="birthday"
onChange={handleInputChange}
/>
<br />
<TextField
id="standard-basic"
label="img"
value={img || ""}
name="img"
type="number"
onChange={handleInputChange}
/>
<Button
style={{ width: "100px" }}
variant="contained"
color="primary"
type="submit"
onChange={handleInputChange}
>
Update
</Button>
</form>
</div>
);
};
export default UserEditForm;
My UserList component:
const UserList = ({ users, history }) => {
const dispatch = useDispatch();
const fetchUsers = async () => {
const response = await axios
.get("http://localhost:3000/characters")
.catch((err) => {
console.log("Err: ", err);
});
dispatch(setUsers(response.data));
};
useEffect(() => {
fetchUsers();
}, []);
console.log(users);
return (
<div>
<button onClick={() => history.goBack()}>...back</button>
<li>
<Link to="/user/add">Add Users</Link>
</li>
{users &&
users.map((user) => {
return (
<div key={user.id}>
<Link to={`users/${user.id}`}> {user.name} </Link>
</div>
);
})}
</div>
);
};
const mapStateToProps = (state) => {
return {
users: state.allUsers.users,
};
};
export default connect(mapStateToProps, null)(UserList);

How can I put a counter up in my form and add data in the databases using reactjs ,formik and axios

I ‘m new in react js
I put a counter up in my form I have problem to put the result of counter with the form result in the databases
I use for my Api mongodb and spring boot
Count up function
export default function Index(props) {
/* Server State Handling */
const [count, setCount] = useState(0);
const [delay, setDelay] = useState(1000);
useInterval(() => setCount((c) => c + 1), delay);
useEffect(() => {
if (delay === null) alert(`Count ${count}`);
}, [count, delay]);
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
let id;
if (delay) {
id = setInterval(savedCallback.current, delay);
}
return () => clearInterval(id);
}, [delay]);
}
const [serverState, setServerState] = useState();
const handleServerResponse = (ok, msg) => {
setServerState({ok, msg});
};
Function of submitting data
const handleOnSubmit = (values, actions) => {
axios.post( "/consultations", values,
)
.then(response => {
props.history.push("/listcons");
actions.setSubmitting(false);
actions.resetForm();
handleServerResponse(true, "Thanks!");
alert("Consultation enregister avec succer");
})
.catch(error => {
actions.setSubmitting(false);
handleServerResponse(false, error.response.data.error);
});
My form with the counter up
I have problem here when I submitted my form in my databases the count value is always 0 (the initial value) how can I resolve this problem what is the problem of my code
return (
<div className="container ">
<div className="card-body bg-white">
<Formik
initialValues={{count:0,titre: ""}}
onSubmit={handleOnSubmit}
validationSchema={formSchema}
>
{({ isSubmitting }) => (
<Form id="fs-frm" noValidate >
<div style={{textAlign: 'center'}}>
<h3>Count</h3>
<h2> {count}</h2>
</div>
<div className="form-group" >
<label htmlFor="titre">Titre</label>
<Field id="titre" name="titre" className="form-control" />
<ErrorMessage name="titre" className="errorMsg" component="p" />
</div>
<Card.Footer style={{ "textAlign": "right" }}>
<button type="submit" className="btn btn-primary" disabled={isSubmitting}>
Submit
</button>
</Card.Footer>
{serverState && (
<p className={!serverState.ok ? "errorMsg" : ""}>
{serverState.msg}
</p>
)}
</Form>
)}
</Formik>
</div>
</div>
);
};

How do I make the invalid hook call go away?

I get this error when trying to npm start my project:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
import React, { useState, useEffect } from 'react';
import './index.css';
import conspireLogo from './conspireLogo.png';
import Post from './Post'
import { auth, db } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Modal from '#material-ui/core/Modal';
import { Button, Input } from '#material-ui/core'
import ImageUpload from './imageUpload';
//import { BrowserRouter, Route, Switch } from 'react-router-dom';
function getModalStyle() {
const top = 50;
const left = 50;
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`,
};
}
const useStyles = makeStyles((theme) => ({
paper: {
position: 'absolute',
width: 400,
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
function MainPage() {
const classes = useStyles();
const [modalStyle] = useState(getModalStyle);
const [posts, setPosts] = useState([]);
const [open, setOpen] = useState(false);
const [openSignIn, setOpenSignIn] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
console.log(authUser);
setUser(authUser);
} else {
setUser(null);
}
})
return () => {
unsubscribe();
}
}, [user,username]);
useEffect(() => {
db.collection('posts').orderBy('timestamp', 'desc').onSnapshot(snapshot => {
setPosts(snapshot.docs.map(doc => ({
id: doc.id,
post: doc.data()
})));
})
}, []);
const signUp = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
authUser.user.updateProfile({
displayName: username
})
})
.catch((error) => alert(error.message));
}
const signIn = (event) => {
event.preventDefault();
auth
.signInWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
setOpenSignIn(false);
}
return (
<div className="app">
<Modal
open={open}
onClose={() => setOpen(false)}
>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
</center>
<Input
placeholder="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<Input
placeholder="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signUp}>Sign Up</Button>
</form>
</div>
</Modal>
<Modal
open={openSignIn}
onClose={() => setOpenSignIn(false)}
>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
</center>
<Input
placeholder="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signIn}>Sign In</Button>
</form>
</div>
</Modal>
<div className="app__header">
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
{user ? (
<Button onClick={() => auth.signOut()}>Logout</Button>
): (
<div className="app__loginContainer">
<Button onClick={() => setOpenSignIn(true)}>Sign In</Button>
<Button onClick={() => setOpen(true)}>Sign Up</Button>
</div>
)}
</div>
<div className="app__footer">
<Button onClick={() => setOpenSignIn(true)}><img
className="app__footerImage"
src="http://www.simpleimageresizer.com/_uploads/photos/bdfbb0d1/346a1f4363e1b59f6860fdce6abc1082_2_15.jpg"
alt="Create"
/>
</Button>
</div>
<div className="app__posts">
<div className="app__postsLeft">
{
posts.map(({id, post}) => (
<Post key={id} postId={id} user={user} username={post.username} caption={post.caption} imageUrl={post.imageUrl}></Post>
))
}
</div>
</div>
{user?.displayName ? (
<ImageUpload username={user.displayName} />
): (
<h3 className="center">Sorry you need to login to upload</h3>
)}
</div>
);
}
export default MainPage;
const [modalStyle] = useState(getModalStyle);
You're storing the function reference, not the function's return. Change it to
const [modalStyle] = useState(getModalStyle());
Moreover as you don't need to change this modalStyle, you don't need to have it in state
<div style={getModalStyle()} className={classes.paper}>
I don't think so there should be any error in this file, please check the other files
ex - Post, ImageUpload

Resources