previous issue
building a rating app using strapi and react throws errors is solved.
But, the records are not getting added to the admin.
can anyone help on this?
This is the code to add and read reviews from strapi admin,
function App() {
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();
//console.log(result.data);
setReviews(result.data.data);
};
fetchData();
}, []);
const createReview = async () => {
try {
//console.log(review);
const data = await api.createReview(review);
setReview([...reviews, data]);
} catch (error) {
//console.log(error);
}
};
let [reviewCount, setreviewCount] = useState([]);
const setCountFxn = (no) => {
setReview(no);
};
return (
<>
<form>
<div style={styles.container}>
<h2>RATE OUR SERVICE</h2>
<div style={styles.stars}>
{stars.map((_, index) => {
return (
<FaStar
key={index}
size={24}
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>
<input
type='text'
placeholder='input your name'
required
style={styles.input}
value={review.Name}
onChange={(e) => setReview({ ...review, Name: e.target.value })}
/>
</div>
<textarea
placeholder="what's your feedback"
required
style={styles.textarea}
value={review.review}
onChange={(e) => setReview({ ...review, review: e.target.value })}
/>
<button type='submit' style={styles.button} className='btn btn-primary' onClick={createReview}>
submit
</button>
</div>
</form>
<section id='reviews'>
<div className='reviews-heading'>
<span>REVIEWS FROM CUSTOMERS</span>
</div>
<div className='container'>
<div className='row'>
{reviews.map((review, i) => (
<div key={review.id} className='col-md-6'>
<div className='reviews-box'>
<div className='box-top'>
<div className='profile'>
<div className='name-user'>
<strong>{review.attributes.Title}</strong>
</div>
</div>
<div style={styles.stars}>
{Array.from({ length: review.attributes.Rating }).map((i) => (
<FaStar key={i} size={18} color={colors.orange} />
))}
</div>
</div>
<div className='client-comment'>{review.attributes.Body}</div>
</div>
</div>
))}
</div>
</div>
</section>
</>
);
}
export default App;
The form gets submitted and reloads after submit, but the record does not get added to strapi admin. I've set the roles of the data to public.
thanks
Nabi
You need a very specific structure to create a new entry with strapi. I assume your payload looks like this:
{
name: 'xyz',
rating: 5
}
Correct would be:
{
data: {
name: 'xyz',
rating: 5
}
}
Strapi Docs - Creating an entry
Ive figured it out!
The values of the form were named wrong. "Name" should be "Title" and "review" should be "Body". It now adds the data to the strapi admin.
Related
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;
Component where my delete button is. i am trying to get to the collection in firestore an delete the post using its id. but nothing shows up. i don't know what i am missing. even if i think the syntax makes sense
function TodoList({id, title, icon}) {
const deleteTodo = ()=>{
db.collection('Todo').doc(id).delete()
}
return (
<div className="todoList" >
<h4 className="title">{title}</h4>
<div className="icons">
{icon && <DeleteIcon className="icon" onClick={deleteTodo} />}
{icon ? <CheckIcon className="icon1"/> : ""}
</div>
</div>
)
}
piece of code where i save the data in database. using db.collection firebase:
function TodoInput() {
const [todos, setTodos] = useState("");
const [saved, setSaved] = useState([]);
useEffect(() => {
db.collection('Todo').orderBy('timestamp', 'desc').onSnapshot(snapshot => {
setSaved(snapshot.docs.map(doc =>({
id: doc.id,
data: doc.data(),
})))
})
}, [])
const handleSubmit = (e)=>{
e.preventDefault();
if(!todos){
}else{
db.collection('Todo').add({
title: todos,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
})
}
setTodos('');}
return (
<div className="todoInput" >
<form >
<input required type="text" placeholder="What to do ?" value={todos}
onChange={(e)=>setTodos(e.target.value)} />
<button type="submit" onClick={handleSubmit} >ADD TODO</button>
</form>
<div className="todoListWrapper">
<div className="todoListItem" >
{saved.map(({id, data:{title}})=>(
<TodoList className="todoList1" key={id} title={title} icon />
))}
</div>
</div>
</div>
)
}
I created a todo app using react and firestore but it is storing my values as string and i want them to be stored as number. Can someone tell what to do, i tried adding Number() but it didn't work. So if anyone could explain what i am doing wrong or how to do it i will be really grateful.
Code :
function SignUp() {
const [recipes, setRecipes] = useState([])
const [form, setForm] = useState({
title: Number(""),
desc: "",
})
const [popupActive, setPopupActive] = useState(false)
const recipesCollectionRef = collection(db, "recipes")
useEffect(() => {
onSnapshot(recipesCollectionRef, snapshot => {
setRecipes(snapshot.docs.map(doc => {
return {
id: doc.id,
viewing: false,
...doc.data()
}
}))
})
}, [])
const handleSubmit = e => {
e.preventDefault()
if (
!form.title ||
!form.desc
) {
alert("Please fill out all fields")
return
}
addDoc(recipesCollectionRef, form)
setForm({
title: Number(""),
desc: "",
})
setPopupActive(false)
}
const removeRecipe = id => {
deleteDoc(doc(db, "recipes", id))
}
return (
<div className="App">
<label>Upload Your Slots</label>
<button onClick={() => setPopupActive(!popupActive)}>Add Slots</button>
<div className="recipes">
{ recipes.map((recipe, i) => (
<div className="recipe" key={recipe.id}>
<h3>{ recipe.title }</h3>
<p dangerouslySetInnerHTML={{ __html: recipe.desc }}></p>
{ recipe.viewing && <div>
</div>}
<div className="buttons">
<button className="remove" onClick={() => removeRecipe(recipe.id)}>Remove</button>
</div>
</div>
))}
</div>
{ popupActive && <div className="popup">
<div className="popup-inner">
<form onSubmit={handleSubmit}>
<div className="form-group">
<label><br></br>From</label>
<input
placeholder="Upload Your Slots In HH:MM 24hr Format"
type="number"
value={form.title}
onChange={e => setForm({...form, title: e.target.value})} />
</div>
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);
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>
);
};