I'm new to react and trying to connect firestore for my project.
I followed the example from the Internet and everything works, the data is deleted and written to the database, also when I change the data they change in the database, but I get errors in the console and a white screen.
Uncaught TypeError: data.map is not a function
If you need any more files or code, I will correct my question, please write which ones I need to add
Also, when loading the page, I get the following error in the console:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. at wrappedSendMessageCallback
Here is the code that throws the error:
export default function Saved({ data, setData }) {
function editData(id, newWord, newTranslate, newNote) {
const editedDataList = async (card) => {
if (id === card.id) {
return {
...card,
word: newWord,
translate: newTranslate,
note: newNote,
};
}
let newFields = {
word: newWord,
translate: newTranslate,
note: newNote,
}
await updateDoc(doc(db, "db-name", id), newFields);
console.log(newFields)
return card;
};
setData(editedDataList);
}
const deletePost = async (id) => {
await deleteDoc(doc(db, "db-name", id));
};
const dataList = data.map((card) => (
<SavedData
id={card.id}
key={card.id}
word={card.word}
translate={card.translate}
note={card.note}
editData={editData}
del={deletePost}
/>
));
return (
<div>
<div className="sec-menu"></div>
<div className="saved-inner">
{data.length >= 1 ? (
<div className="saved-list">{dataList}</div>
) : (
<Link className="main-btn" to="/addcard">
Add
</Link>
)}
</div>
</div>
);
}
Here Menu.js code:
function Menu() {
const [data, setData] = useState([]);
useEffect(() => {
const q = query(collection(db, "db-name"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
let wordsArr = [];
querySnapshot.forEach((doc) => {
wordsArr.push({ ...doc.data(), id: doc.id });
});
setData(wordsArr);
});
return () => unsubscribe();
}, []);
return (
<div className="content">
<AuthContextProvider>
<Routes>
<Route
path="saved"
element={<Saved data={data} setData={setData} />}
/>
</Route>
</Routes>
</AuthContextProvider>
</div>
);
}
export default Menu;
On second glance, the issue is where you call setData(editedDataList). You're passing in a function into this method which is in turn updating data to be a function instead of an array. Try changing, editData() to be something like this:
const editData = async (id, newWord, newTranslate, newNote) => {
const editedDataList = await Promise.all(data.map(async (card) => {
let newFields = {
word: newWord,
translate: newTranslate,
note: newNote,
};
if (id === card.id) {
return { ...card, ...newFields };
}
await updateDoc(doc(db, "db-name", id), newFields);
console.log(newFields);
return card;
}));
setData(editedDataList);
};
editedDataList will be an array of the modified cards in the original and setData() should work as expected.
maybe the error occurs because "data" object is not an array.
And check what are you setting on "setData(editedDataList);" instruction
Related
I am trying to write a program that communicates with the client frequently and I need to quickly notice the changes and read the result from the server. But this request is constantly being sent and loaded, even when the user is not interacting. And this causes the user's system to be occupied.
this is mu code:
const AdminDashboard = () => {
const [filterShow, setFilterShow] = useState({ sort: "", read: "", flag: "", skip: 0, limit: 15 });
const [adminItemList, setAdminItemList] = useState([]);
const [searchParams, setSearchParams] = useSearchParams();
async function changeItem(updateItem) {
// update admin item state
await axios.put("{...}/api/admin", { ... });
}
useEffect(() => {
async function resultItem() {
// get result(admin items)
await axios.get(`{...}/api/admin?${searchParams.toString()}`)
.then((res) => {
setAdminItemList(res.data.data);
}).catch((res) => {
console.log(res)
});
}
resultItem();
})
return (<>
{adminItemList.map((ai, i) => {
return (<div key={i}>
<AdminItem item={ai} count={i} skip={filterShow.skip} res={changeItem} />
</div>)
})}
</>);
}
I know that I can avoid resending the request by using "useEffect" and passing an empty array to its second input. But I need to listen the changes so I can't do that.
How can i listening the changes and prevent repeated get requests???
The only solution I could find:
I moved the function "resultItem" outside of useEffect. And I wrote useEffect with an empty array in the second entry. then call "resultItem" in useEffect.
I gave this function "resultItem" an input to receive a query so that it can be flexible
I called it wherever I needed it
Note: In async functions, I first put that function in the Promise and call the "resultItem" in then().
I will put all the written codes here:
const AdminDashboard = () => {
const usePuCtx = useContext(PublicContext);
const { lang, dir } = usePuCtx.language;
// base state
const [allAdminItem, setAllAdminItem] = useState(0);
const [filterShow, setFilterShow] = useState({ sort: "", read: "", flag: "", skip: 0, limit: 3 });
const [adminItemList, setAdminItemList] = useState([]);
// validate for show this page
const [isAdmin, setIsAdmin] = useState(false);
const [searchParams, setSearchParams] = useSearchParams();
async function setResalt(radioName, radioState) {
// set setting on query for get result(admin items)
let newFilter = { ...filterShow };
newFilter[radioName] = radioState;
const queryStr = queryString.stringify(newFilter);
setSearchParams(queryStr);
new Promise((res, rej) => { res(setFilterShow(newFilter)) })
.then(() => resultItem(queryStr));
}
async function changeItem(updateItem) {
// update admin item state (read & flag)
await axios.put(usePuCtx.ip_address + "/api/admin",
{ _id: updateItem._id, read: updateItem.read, flag: updateItem.flag })
.then(() => resultItem(searchParams));
}
function showSkipPage(numberPage) {
const nextResult = numberPage * filterShow.limit
setResalt("skip", nextResult)
}
async function resultItem(query) {
// get result(admin items)
await axios.get(usePuCtx.ip_address + `/api/admin?${query.toString()}`)
.then((res) => {
setIsAdmin(true);
setAdminItemList(res.data.data);
}).catch(() => {
// if auth token is wrong
window.location = "/not-found";
});
// get all admin item number
await axios.get(usePuCtx.ip_address + "/api/admin?limit=0&skip=0&flag=&read=&sort=close")
.then((res) => {
setIsAdmin(true);
setAllAdminItem(res.data.data.length);
}).catch(() => {
// if auth token is wrong
window.location = "/not-found";
});
}
useEffect(() => {
resultItem(searchParams);
}, []);
return (!isAdmin ? "" : (<>
<div className="container-fluid" dir={dir}>
<div className="row m-4" dir="ltr">
{/* radio buttons */}
<RadioFilterButton name="read" id1="read-" id2="read-false" id3="read-true"
inner1={txt.radio_filter_button_all[lang]} inner2={txt.radio_filter_button_read_no[lang]}
inner3={txt.radio_filter_button_read[lang]} res={setResalt} />
<RadioFilterButton name="flag" id1="flag-" id2="flag-false" id3="flag-true"
inner1={txt.radio_filter_button_all[lang]} inner2={txt.radio_filter_button_flag_no[lang]}
inner3={txt.radio_filter_button_flag[lang]} res={setResalt} />
<RadioFilterButton name="sort" id1="sort-close" id2="sort-far"
inner1={txt.radio_filter_button_close[lang]} inner2={txt.radio_filter_button_far[lang]}
res={setResalt} />
</div><hr />
<div className="m-4" style={{ minHeight: "100vh" }}>
{
// show result(admin items)
adminItemList.map((ai, i) => {
return (<div key={i}>
<AdminItem item={ai} count={i} skip={filterShow.skip} res={changeItem} />
</div>)
})
}
</div>
<div className="row justify-content-center mt-auto" dir="ltr">
<PageinationTool countAll={allAdminItem} limitCard={filterShow.limit} skipNum={filterShow.skip} res={showSkipPage} />
</div>
<Footer />
</div>
</>));
}
I was wonder what I'm doing wrong here.
I'm getting this error: "Rendered more hooks than during the previous render."
export default function ProductDetails() {
//Use State
const {qty, increaseQty, decreaseQty, onAdd, setQty} = useStateContext();
//Reset Qty
useEffect(() => {
setQty(1);
}, []);
//Fetch Slug
const {query} = useRouter();
//Fetch Graphql data
const [results] = useQuery({
query: GET_PRODUCT_QUERY,
variables: {slug: query.slug}
})
const {data, fetching, error} = results;
//Check for data coming in
if(fetching) return <p>Loading...</p>;
if(error) return <p>Oh no....</p>;
//Extract Product Data
const {title,description, image, gallery } = data.products.data[0].attributes;
const [img, setImg] = useState(gallery.data[0].attributes.formats.medium.url);
console.log(img);
//Create a toast
const notify = () => {
toast.success(`${title} added to your cart`, {duration: 1500});
}
return(
<DetailsStyle>
<Gallery>
<img src={gallery.data[0].attributes.formats.medium.url} alt={title} />
<Thumbnails>
{gallery.data.map((image, index) => (
<SingleThumb key={index} >
<img src={image.attributes.formats.thumbnail.url} alt={title} />
</SingleThumb>
)
)}
</Thumbnails>
</Gallery>
<ProductInfo>
<h3>{title}</h3>
<p>{description}</p>
<Quantity>
<span>Quantity</span>
<button><AiFillMinusCircle onClick={decreaseQty} /></button>
<p>{qty}</p>
<button><AiFillPlusCircle onClick={increaseQty}/></button>
</Quantity>
<Buy onClick={() => {
onAdd(data.products.data[0].attributes, qty)
notify();
}}>Add To Cart</Buy>
</ProductInfo>
</DetailsStyle>
)
}
Something wrong is in this line: const [img, setImg] = useState();
Why I can't use more hooks here.
Does anyone know why I'm getting this?
You are using early return
and this line of code won't execute every time:
const [img, setImg] = useState(gallery.data[0].attributes.formats.medium.url);
This is only conditionally called:
const [img, setImg] = useState(gallery.data[0].attributes.formats.medium.url);
Because the component has earlier conditional return statements. Move it to earlier in the function. (Generally I invoke useState operations right away.)
Hooks need to always be consistently called in the same order on every render.
You declare your state after some return statements. It means that if you had any errors or you were in loading state, the state is not defined. But maybe in the next render, the data is set and then your state will be defined with the inital value (gallery.data[0].attributes.formats.medium.url).
It's forbidden in react because all of the hooks should always be in the same order on every single render. In order to fix this, you should change the place of your useState for img.
Hope it helps:
export default function ProductDetails() {
const [img, setImg] = useState('');
//Use State
const {qty, increaseQty, decreaseQty, onAdd, setQty} = useStateContext();
//Reset Qty
useEffect(() => {
setQty(1);
}, []);
//Fetch Slug
const {query} = useRouter();
//Fetch Graphql data
const [results] = useQuery({
query: GET_PRODUCT_QUERY,
variables: {slug: query.slug}
})
const {data, fetching, error} = results;
//Check for data coming in
//Extract Product Data
useEffect(() => {
if(results && results.data) {
const {data} = results
const { gallery } = data.products.data[0].attributes;
setImg(gallery.data[0].attributes.formats.medium.url);
}
}, [results]);
useEffect(() => {
console.log(img);
}, [img]);
//Create a toast
const notify = (title) => {
toast.success(`${title} added to your cart`, {duration: 1500});
}
if(fetching) {
return <p>Loading...</p>;
} else if(error) {
return <p>Oh no....</p>;
} else if(data) {
const { title, description, image, gallery } = data.products.data[0].attributes;
return(
<DetailsStyle>
<Gallery>
<img src={gallery.data[0].attributes.formats.medium.url} alt={title} />
<Thumbnails>
{gallery.data.map((image, index) => (
<SingleThumb key={index} >
<img src={image.attributes.formats.thumbnail.url} alt={title} />
</SingleThumb>
)
)}
</Thumbnails>
</Gallery>
<ProductInfo>
<h3>{title}</h3>
<p>{description}</p>
<Quantity>
<span>Quantity</span>
<button><AiFillMinusCircle onClick={decreaseQty} /></button>
<p>{qty}</p>
<button><AiFillPlusCircle onClick={increaseQty}/></button>
</Quantity>
<Buy onClick={() => {
onAdd(data.products.data[0].attributes, qty)
notify(title);
}}>Add To Cart</Buy>
</ProductInfo>
</DetailsStyle>
)
} else {
return null;
}
}
There should be no return before hooks.
These lines
if(fetching) return <p>Loading...</p>;
if(error) return <p>Oh no....</p>;
should be after all hooks
I have a list of user on a page , what i want to achieve is render user detail when i click on the link with his id. for that i have tried to send the id and retrieve the data with a new request like this :
My routes :
<Route path='/coupeurs' element={<Coupeurs />} />
<Route path='/coupeurs/add' element={<AddCoupeur />} />
<Route path='/coupeurs/:id' element={<Coupeur />} />
My list :
<ul>
{coupeurs.map(coupeur => (
<li key={coupeur.id}>
{coupeur.nom} {coupeur.prenom}
<div className='coupeur-actions'>
<Link to={`/coupeurs/${coupeur.id}`}>Voir</Link>
<Link to={`/coupeurs/${coupeur.id}/edit`}>Editer</Link>
</div>
</li>
))}
</ul>
the place where i want display details :
export default function Coupeur(props) {
console.log(props);
let { id } = useParams();
const [coupeur, setCoupeur] = useState(getCoupeurInfoById(id));
console.log(coupeur);
return (
<div>
<h3>Identifiant : {id}</h3>
<h3>Nom : {coupeur.nom}</h3>
<h3>Prenom : {coupeur.prenom}</h3>
<h3>Statut : {coupeur.statut}</h3>
</div>
)
}
My getCoupeurInfoById function :
export async function getCoupeurInfoById(id) {
const docRef = doc(db, "coupeurs", id);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
return docSnap.data();
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}
i get my page without the info , but when i console log my variable i can see the result !
Can you help me found the right way to do that kind of things ? thank you
Since getCoupeurInfoById is an async function it implicitly returns a Promise object and subsequently (quickly) resolves and mutates the coupeur state variable. When you log it you see the resolved value.
The useState hook expects a synchronous function that returns the initial state value.
Use a useEffect hook to handle the side-effect of fetching/computing the coupeur value.
Example:
export default function Coupeur(props) {
const { id } = useParams();
const [coupeur, setCoupeur] = useState(); // <-- initially undefined
useEffect(() => {
const getCoupeur = async () => {
try {
const coupeur = await getCoupeurInfoById(id);
setCoupeur(coupeur);
} catch(error) {
// handle any rejections/errors/etc
}
};
getCoupeur(); // <-- fetch/compute coupeur value
}, [id]);
if (!coupeur) return null; // or loading indicator/etc
return (
<div>
<h3>Identifiant : {id}</h3>
<h3>Nom : {coupeur.nom}</h3>
<h3>Prenom : {coupeur.prenom}</h3>
<h3>Statut : {coupeur.statut}</h3>
</div>
)
}
I'm trying to update elements after deletion, without refreshing a page. Currently, if delete a record, need to refresh a page to see the result. As I understand, need to update useState, but I do not understand how to do it. If I loop useEffect it works but slowly, but I think it's not the best idea to loop get response.
Get all records from a database.
const PostsGetUtill = () => {
const [posts, setPosts] = useState([]);
const fetchPosts = () => {
axios.get("api/v1.0/post/get").then(response => {
console.log(response.data);
setPosts(response.data);
}).catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
};
useEffect(() => {
fetchPosts();
}, []); // }, [fetchPosts]); <--- working well with loop
return (
<section className="container-post">
<PostMansonry posts={posts} columns={3} />
</section>
);
};
export default PostsGetUtill;
Sort and map records
export default function PostMansonry({ posts, columns }) {
return (
<section className="masonry" style={{ gridTemplateColumns: `repeat(${columns}, minmax(275px, 1fr))` }}>
{posts.sort((a, b) => a.zonedDateTime < b.zonedDateTime ? 1 : -1).map((posts, index) =>
<MasonryPost {...{ posts, index, key: index }} />)
}
</section>
)
}
Put data to the card
export default function MasonryPost({ posts, index }) {
return (
<div key={index} className="masonry-post">
<div className="card">
<div className="card-body">
<h5 className="card-title">{posts.title}</h5>
<p className="card-text">{posts.description}</p>
<p className="card-text"><small className="text-muted"> {posts.zonedDateTime}</small></p>
<div><button type="button" onClick={(e) => PostsDeleteUtill(posts.post_Id)} className="btn btn-danger">Delete</button></div>
</div>
</div>
</div>
)
}
Deleting
const PostsDeleteUtill = async (post_Id) => {
axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
console.log(response);
}).catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log('error config', error.config);
});
};
export default PostsDeleteUtill;
Basically what you need to do is, in your PostsDeleteUtill function, in the promise return of your axios.delete, you need to update your posts state, which is set in PostsGetUtill.
In order to do that, you have 2 options:
Use a global state (React Context, Redux, etc)
Pass your setPosts handle all the way to your PostsDeleteUtill
I think option 1 is a bit cleaner for your specific case, but if you don't need global state anywhere else in your project, maybe it is fine to have a not so clean solution instead of implementing the whole global state structure for only one thing.
Option 1 pseudo code:
Your PostsGetUtill component would use a global state instead of local state:
const PostsGetUtill = () => {
// Remove this:
// const [posts, setPosts] = useState([]);
const fetchPosts = () => {
axios.get("api/v1.0/post/get").then(response => {
console.log(response.data);
// Instead of a local "setPosts" you would have a global
// "setPosts" (in Redux, this would be a dispatch)
dispatch({type: "PUT_POSTS", action: response.data})
}).catch(function (error) {
// No changes here...
});
};
// This runs only the first time you load this component
useEffect(() => {
fetchPosts();
}, []);
// Use your global state here as well:
return (
<section className="container-post">
<PostMansonry posts={globalState.posts} columns={3} />
</section>
);
};
export default PostsGetUtill;
In your PostsDeleteUtill function:
const PostsDeleteUtill = async (post_Id) => {
axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
// Update global state here. Probably filter the data to remove
// the deleted record
const updatedPosts = globalState.posts.filter(post => post.id !== response.data.id)
}).catch((error) => {
// No changes here
});
};
export default PostsDeleteUtill;
Option 2 pseudo code:
In your PostsGetUtill component, create and pass on a handleRemovePost:
// Your existing code ...
const handleRemovePost = (postID) => {
const filteredPosts = posts.filter(post => post.id !=== postID)
setPosts(filteredPosts)
}
return (
<section className="container-post">
<PostMansonry posts={posts} columns={3} handleRemovePost={handleRemovePost} />
</section>
);
In your PostMansonry, pass on again your handleRemovePost
export default function PostMansonry({ posts, columns, handleRemovePost }) {
return (
// Your existing code ...
<MasonryPost {...{ posts, index, key: index, handleRemovePost }} />)
)
}
Again in your MasonryPost
export default function MasonryPost({ posts, index, handleRemovePost }) {
return (
// Your existing code ...
<button type="button" onClick={(e) => PostsDeleteUtill(posts.post_Id, handleRemovePost)} className="btn btn-danger">Delete</button>
)
}
And finally:
const PostsDeleteUtill = async (post_Id, handleRemovePost) => {
axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
handleRemovePost(response);
})
};
PS: Please note that I only added a pseudo-code as a reference, trying to point out specific parts of the code that needs to be updated. If you need more information about global state, you can check React Context and Redux
What the below code does is to get data from API, and then render it on the page. searchChange function takes a value from the input tag, and setValue for query state. My api endpoint takes argument to filter the API such as http://127.0.0.1:8000/api/deals/?q=${query}.
I'm very confused how I can update the DealList component with the API updated with query state whenever typing something in the input tag. I'm thinking of that I need to something in searchChange function, but not sure what to do there.
index.js
const useFetch = (url, query, defaultResponse) => {
const [result, setResult] = useState(defaultResponse);
const getDataFromAPI = async url => {
try {
const data = await axios.get(url);
setResult({
isLoading: false,
data
});
} catch (e) {}
};
useEffect(() => {
if (query.length > 0) {
getDataFromAPI(`${url}?q=${query}`);
} else {
getDataFromAPI(url);
}
}, []);
return result;
};
const Index = ({ data }) => {
const query = useInput("");
const apiEndpoint = "http://127.0.0.1:8000/api/deals/";
const dealFetchResponse = useFetch(apiEndpoint, query, {
isLoading: true,
data: null
});
const searchChange = e => {
query.onChange(e);
query.setValue(e.target.value);
};
return (
<Layout>
<Head title="Home" />
<Navigation />
<Container>
<Headline>
<h1>The best lease deal finder</h1>
<h4>See all the lease deals here</h4>
</Headline>
<InputContainer>
<input value={query.value} onChange={searchChange} />
</InputContainer>
{!dealFetchResponse.data || dealFetchResponse.isLoading ? (
<Spinner />
) : (
<DealList dealList={dealFetchResponse.data.data.results} />
)}
</Container>
</Layout>
);
};
export default Index;
The biggest challenge in something like this is detecting when a user has stopped typing.. If someone is searching for 'Milk' - when do you actually fire off the API request? How do you know they aren't searching for 'Milk Duds'? (This is hypothetical, and to demonstrate the 'hard' part in search bars/APIs due to their async nature)..
This is typically solved by debouncing, which has been proven to work, but is not very solid.
In this example, you can search Github repos...but even in this example, there are unnecessary requests being sent - this is simply to be used as a demonstration. This example will need some fine tuning..
const GithubSearcher = () => {
const [repos, setRepos] = React.useState();
const getGithubRepo = q => {
fetch("https://api.github.com/search/repositories?q=" + q)
.then(res => {
return res.json();
})
.then(json => {
let formattedJson = json.items.map(itm => {
return itm.name;
})
setRepos(formattedJson);
});
}
const handleOnChange = event => {
let qry = event.target.value;
if(qry) {
setTimeout(() => {
getGithubRepo(qry);
}, 500);
} else {
setRepos("");
}
};
return (
<div>
<p>Search Github</p>
<input onChange={event => handleOnChange(event)} type="text" />
<pre>
{repos ? "Repo Names:" + JSON.stringify(repos, null, 2) : ""}
</pre>
</div>
);
};
ReactDOM.render(<GithubSearcher />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>