React doesn't display initial state of UI on start - javascript

I'm building an E-commerce app with React and I stumbled on a problem that React doesn't render the UI based on the initial state when first start the page.
Problem description:
I have a sort state which has the initial state of "latest", based on this Sorting functionality - if sort has a value of "latest" - it will sort and return the newest items first.
But on start or when I refresh the page, the default value and state of sort will still be "latest" but the UI just display the oldest items first.
I have to click on other option and then choose the Latest option again for the sort logic to go through. When I refresh the page, the problem is back.
The logic for sorting other values works fine. In the demo below, you can see I log out the sort current state. On start, the sort value is already "latest".
In the API product.js file, I already sorted the items with mongoose by the field createdAt - 1 but seems like it doesn't apply on the UI?
-> What would be the case here that makes React not render the items based on initial state and how can we fix it?
Below is my code:
ProductList.jsx
const ProductList = () => {
const location = useLocation()
const category = location.pathname.split("/")[2]
const [filters, setFilters] = useState({});
const [sort, setSort] = useState("latest");
// For Filters Bar
const handleFilters = (e) => {
const value = e.target.value
// When choosing default value, show all products:
if (value === "") {
return setFilters([])
} else {
setFilters({
...filters,
[e.target.name]: value,
})
}
}
return (
<Container>
<Navbar />
<Announcement />
<Title>Dresses</Title>
<FilterContainer>
<Filter>
<FilterText>Filter Products: </FilterText>
<Select name="color" onChange={handleFilters}>
<Option value="">All Color</Option>
<Option value="white">White</Option>
<Option value="black">Black</Option>
<Option value="brown">Brown</Option>
<Option value="red">Red</Option>
<Option value="blue">Blue</Option>
<Option value="yellow">Yellow</Option>
<Option value="green">Green</Option>
</Select>
<Select name="size" onChange={handleFilters}>
<Option value="">All Size</Option>
<Option>XS</Option>
<Option>S</Option>
<Option>M</Option>
<Option>L</Option>
<Option>XL</Option>
<Option>36</Option>
<Option>37</Option>
<Option>38</Option>
<Option>39</Option>
<Option>40</Option>
<Option>41</Option>
<Option>42</Option>
<Option>43</Option>
</Select>
</Filter>
<Filter>
<FilterText>Sort Products: </FilterText>
<Select onChange={e => setSort(e.target.value)}>
<Option value="latest">Latest</Option>
<Option value="oldest">Oldest</Option>
<Option value="asc">Price ↑ (Low to High)</Option>
<Option value="desc">Price ↓ (High to Low)</Option>
</Select>
</Filter>
</FilterContainer>
<Products category={category} filters={filters} sort={sort} />
<Newsletter />
<Footer />
</Container>
);
}
Products.jsx
const Products = ({ category, filters, sort }) => {
const [products, setProducts] = useState([])
const [filteredProducts, setFilteredProducts] = useState([])
useEffect(() => {
const getProducts = async () => {
try {
const res = await axios.get( category
? `http://localhost:5000/api/products?category=${category}`
: `http://localhost:5000/api/products`
)
setProducts(res.data)
} catch (err) {
console.log(`Fetch all items failed - ${err}`)
}
}
getProducts()
}, [category])
useEffect(() => {
category && setFilteredProducts(
products.filter(item =>
Object.entries(filters).every(([key, value]) =>
item[key].includes(value)
)
)
)
}, [category, filters, products])
// Sorting:
useEffect(() => {
console.log(sort)
if (sort === "latest") {
setFilteredProducts(prev =>
[...prev].sort((a, b) => b.createdAt.localeCompare(a.createdAt))
)
} else if (sort === "asc") {
setFilteredProducts(prev =>
[...prev].sort((a, b) => a.price - b.price)
)
} else if (sort === "desc") {
setFilteredProducts(prev =>
[...prev].sort((a, b) => b.price - a.price)
)
} else {
setFilteredProducts(prev =>
[...prev].sort((a, b) => a.createdAt.localeCompare(b.createdAt))
)
}
}, [sort])
return (
<Container>
<Title>Popular In Store</Title>
<ProductsWrapper>
{filteredProducts.map(item => (
<Product key={item._id} item={item} />
))}
</ProductsWrapper>
</Container>
);
}
API Route - product.js
const router = require('express').Router()
const { verifyTokenAndAdmin } = require('./verifyToken')
const Product = require('../models/Product')
// .... (Other CRUD)
// GET ALL PRODUCTS
router.get("/", async(req, res) => {
const queryNew = req.query.new
const queryCategory = req.query.category
try {
let products = []
if(queryNew) {
products = await Product.find().sort({ createdAt: -1 }).limit(5)
} else if (queryCategory) {
products = await Product.find({
categories: {
$in: [queryCategory],
},
})
} else {
products = await Product.find()
}
res.status(200).json(products)
} catch(err) {
res.status(500).json(`Cannot fetch all products - ${err}`)
}
})
module.exports = router
Demo:
Explain demo: On start, it renders oldest items first. Have to choose another option and then return to the latest option for it to render. But in the console, the initial state of sort is already "latest" but it doesn't match with the useEffect sorting logic.
Update
According #idembele70's answer, I mistyped the initial state of filters to Array.
I have fixed it and also added a name="sort" on the Sort select.
I also replaced value="latest" with defaultValue="latest" for my Sort select bar. -> This makes the Latest option stop working so I don't think it can be used in this case?
The result is still the same, the UI doesn't render the logic of the Sort bar to display the latest items first.
Code
const ProductList = () => {
const location = useLocation()
const category = location.pathname.split("/")[2]
const [filters, setFilters] = useState({});
const [sort, setSort] = useState("latest");
const handleFilters = (e) => {
const value = e.target.value
// When choosing default value, show all products:
if (value === "") {
setFilters({}) // Changed from array to object
} else {
setFilters({
...filters,
[e.target.name]: value,
})
}
}
...
<Filter>
<FilterText>Sort Products: </FilterText>
<Select name="sort" onChange={e => setSort(e.target.value)} >
<Option defaultValue="latest">Latest</Option>
<Option value="oldest">Oldest</Option>
<Option value="asc">Price ↑ (Low to High)</Option>
<Option value="desc">Price ↓ (High to Low)</Option>
</Select>
</Filter>

You shouldn't put the changed products to the state, as it makes it extra complex to keep it updated and you need to deal with various useEffect cases. Instead it's better to define sorting and filtering functions and apply them at the render time. This way you'll ensure the render result is always up-to-date with the data:
const filterProducts = (products) => {
if (!category) {
return products;
}
return products.filter(item =>
Object.entries(filters).every(([key, value]) =>
item[key].includes(value),
),
);
};
const sortProducts = (products) => {
switch (sort) {
case "asc":
return [...products].sort((a, b) => a.price - b.price);
case "desc":
return [...products].sort((a, b) => b.price - a.price);
case "latest":
default:
return [...products].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
};
return (
<Container>
<Title>Popular In Store</Title>
<ProductsWrapper>
{sortProducts(filterProducts(products)).map(item => (
<Product key={item._id} item={item} />
))}
</ProductsWrapper>
</Container>
);

If you put log inside your useEffect hooks, I would assume the execution order is:
[sort]->[category]->[category, filters, products]
The useEffect of [category] has an ajax call and it will definitely take effect after [sort], when it taking effect, it will run your query which is not using req.query.new, so it will just run this branch(i guess you do have category)
else if (queryCategory) {
products = await Product.find({
categories: {
$in: [queryCategory],
},
})
}
, it should default return a ascending list just match 'oldest' option.
So in general, your sort effect is not working at all on initial load because it will always get overwritten by other effects.
So either you make all the query with default descending condition to match the default 'latest' option, or you could trigger sort after any query was performed, option 2 looks better but you need to consider what's your expected behavior of sort when changing other elements(filter, category).

i faced a problem with this code from lama, so first i see a error from you define useState with a initialState as object and in your handleFilters you use an array
const [filters, setFilters] = useState({}); // you use Object there
const handleFilters = (e) => {
const value = e.target.value
products:
if (value === "") {
return setFilters([]) //. you should use object there not array.
} else {
setFilters({
...filters,
[e.target.name]: value,
})
}}
So in React when you use onChange it's recommended to use a value or defaultValue in your html elems
to solve this problem take a look to this CodeSandebox link: https://codesandbox.io/s/determined-hopper-gp9ym9?file=/src/App.js
Let me know if it has solved your problem.

Related

My sort is not being rerendered as I want to sort datas according to the user selection

My sorting is working but sometimes my data doesnot change as I select the option no change occurs , I guess I am not using useEffect correctly So I want what am I doing wrong , I am very confused
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
property?.map((item) => (
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}
I think your problem is you're using property?.map which is always referred to your original list.
For a possible fix, you could modify it to data?.map which is your sorted list.
And you also need to set a default value for data
const [data, setData] = useState(property); //`property` is from your fetched data
Full change can be
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
const [data, setData] = useState(property); //set `property` as your default data
const [sortType, setSortType] = useState('rating');
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
const displayedData = data?.length ? data : property //check if data is available
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
displayedData?.map((item) => ( //the main change is here
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}

dom elements not re-rendering when state changes

I'm creating a simple app that queries an api that returns a list of books when you search by title. I am adding the option to sort the search results.
When a user searches for a title, eg 'harry potter', the app stores an array of books in state and renders the results.
When a user then selects the option to sort (eg by title), my array of books in state is correctly being sorted and updated, but the old unsorted books are the ones shown.
Notably, if I then select to sort by date, this time I am seeing sorted books being displayed by it's the books sorted by title not date!
And also, at all times, the value of my books array is correctly sorted, but the books being displayed are not (it's essentially the previous state of books which is being rendered).
This is observable if you keep switching between title and sort, the app will update, but the results will be sorted by title when you try to sort by date and vice versa.
It's almost as if when I select a sort option, the dom is rerendering, and then I'm changing the value of books in state, but that isn't then again causing a re-rendering of the dom.
Any ideas what might be going wrong?
sandbox
The code:
export default function App() {
const [input, setInput] = useState("");
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(false);
const [sort, setSort] = useState("");
const API_URL = `https://openlibrary.org/search.json?title=`;
const sortFn = (books, sortType) => {
setLoading(true);
if (sortType === "title") {
console.log("sorting by title!");
const sortedBooks = books.sort((a, b) => a.title.localeCompare(b.title));
setBooks(sortedBooks);
} else if (sortType === "publishDate") {
console.log("sorting by date, most recent");
const sortedBooks = books.sort((a, b) => {
const dateA = new Date(a.publishDate);
const dateB = new Date(b.publishDate);
return dateB - dateA;
});
console.log("sorted books:", sortedBooks);
setBooks(sortedBooks);
}
setLoading(false);
};
const getBooks = async (queryStr) => {
setLoading(true);
try {
const {
data: { docs }
} = await axios.get(`${API_URL}${queryStr}`);
// console.log(docs);
const slice = docs.slice(0, 10);
const results = slice.map((item) => ({
title: item.title,
author: item.author_name[0],
isbn: item.isbn[0].trim(),
publishDate: item.publish_date[0]
}));
if (sort) {
sortFn(results, sort);
} else {
setBooks(results);
}
setLoading(false);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
if (books && sort) sortFn(books, sort);
}, [sort]);
const changeHandler = (e) => {
setInput(e.target.value);
};
const selectChange = (e) => {
setSort(e.target.value);
};
const submitHandler = (e) => {
e.preventDefault();
if (input) {
//must replace whitespace within string with '+' symbol
const query = input.trim().replace(" ", "+");
getBooks(query);
}
setInput("");
};
console.log("books:", books);
const tiles = books.map((book) => (
<Book
key={book.isbn}
title={book.title}
author={book.author}
publishDate={book.publishDate}
imgURL={`https://covers.openlibrary.org/b/isbn/${book.isbn}-M.jpg`}
/>
));
return (
<div className="App">
<form onSubmit={submitHandler}>
<input type="text" value={input} onChange={changeHandler} />
<button type="submit">Submit</button>
</form>
<select onChange={selectChange}>
<option value="">Sort by</option>
<option value="title">Title(A-Z)</option>
<option value="publishDate">Publish Date</option>
</select>
{loading && <div>Loading</div>}
{!loading && books ? tiles : null}
</div>
);
}

ActiveRecord::RecordInvalid Exception: Validation failed: "Something" must exist

I am adding all is needed to create a post, but am getting an error message saying "Facility must exist."
For some reason, the facility_id is capturing the name of the facility and not the ID.
I am setting state for facilities, and mapping / filtering for my dropdown. Please see below:
function AddPostForm({ posts, handlePost})
{
const [facilities, setFacilities] = useState ([])
const [procedures, setProcedures] = useState ([])
const uniques = procedures.map(procedure => procedure.procedure)
.filter((value, index, self) => self.indexOf(value) === index )
// console.log("unique procedures:", uniques)
const uniqFacility = facilities.map(facility => facility.name).filter((value,index, self) => self.indexOf(value) === index)
useEffect(() => {
fetch(`/posts/${procedures}`)
.then((r) => r.json())
.then(setProcedures);
}, []);
useEffect(() => {
fetch("/facilities")
.then((r) => r.json())
.then(setFacilities);
}, []);
const [formData, setFormData] = useState({
facility_id: "",
procedure:'',
date_of_procedure:'',
date_of_invoice:'',
patient_cost: "",
insurance_cost: "",
comments: ""
})
const { id } = useParams();
function handleChange(event) {
setFormData({
...formData,[event.target.name]: event.target.value,
});
}
function handleSubmit(event) {
event.preventDefault();
handlePost(formData)
return (
<div >
<form onSubmit={handleSubmit}>
<label htmlFor="facility_id">Facility:</label>
<select
id="facility_id"
name="facility_id"
value={formData.facility_id}
onChange={handleChange} >
<option value="">Select Facility</option>
{uniqFacility.map((facility) => (
<option key={facility.id} value={facility.name}>
{facility}
</option>
))}
</select>
</form>
</div>
);
}
export default AddPostForm;
When I check params in the byebug I see facility_id=>"Name of Facility", and get an error message saying that Facility must exist. I tried adjusting the map / filter function to ...facility => facility.id).filter ... , which ends up giving me the facility_id and creates the post as if the name of the entity was its id.
I think I need to adjust the map/filter formula, but I do not know how. Appreciate if someone help me out here.

Really weird state behaviour when trying to set it [duplicate]

I am trying to sort JSON object by date and number. Everything is working fine when i console log but the state is not getting updated on the GUI side. What am i missing? I am using the functional components.
Here is the code...
const Posts = () => {
const [dummyData, setDummyData] = useState(Data);
const sortList = (e) => {
if (e.target.value === "date") {
handleSort();
} else if (e.target.value === "upvotes") {
byUpvotes();
}
};
const handleSort = () => {
const sortedData = dummyData.sort((a, b) => {
const c = new Date(a.published);
const d = new Date(b.published);
if (c.getDate() > d.getDate()) {
return c;
} else {
return d;
}
});
setDummyData(sortedData);
console.log(sortedData);
};
const byUpvotes = () => {
const sortByName = dummyData.sort((a, b) => {
return b.upvotes - a.upvotes;
});
setDummyData(sortByName);
console.log(sortByName);
};
return (
<div>
{dummyData.map((post) => (
<PostsItem key={post.id} post={post} />
))}
<div className="row">
<div className="col-s6">
<label>Browser Select</label>
<select className="browser-default" onChange={sortList}>
<option disabled selected>
Choose your option
</option>
<option value="date">Date</option>
<option value="upvotes">Upvotes</option>
</select>
</div>
</div>
</div>
);
};
The sort function does not create a new array, it mutates the old one. So you're rearranging the existing state, and then setting state with the same array. Since it's the same array, react thinks the state hasn't changed and skips rendering.
Instead, you will need to make a copy of the array and then sort that. For example:
const byUpvotes = () => {
const sortByName = [...dummyData];
sortByName.sort((a, b) => {
return b.upvotes - a.upvotes
})
setDummyData(sortByName)
}

Issues With Filtering and Re-Displaying Data ReactJS

I'm trying to filter through the RandomUser api to display either males or females. My current issue is that I can't display the filtered data like I did the original data.
Here's my current code:
const [data, setData] = useState('');
const [gender, setGender] = useState('');
useEffect(() => {
fetch(`https://randomuser.me/api/?results=500`)
.then(response => response.json())
.then(setData);
}, [])
const FilterData = () => {
if(gender) {
var searchedResult
searchedResult = data.results.filter(
(e) => e.gender === gender
);
console.log(searchedResult)
console.log(gender)
setData([searchedResult])
}
}
if(data.results){
return (
<div>
<div>
<select name="Gender" onChange={(e) => setGender(e.target.value)}>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<button onChange={FilterData()}></button>
</div>
<ul>
{data.results.map(results => (
<li key={results}>
<p>{results.name.first} {results.name.last}</p>
<img src={results.picture.medium}></img>
</li>
))}
</ul>
</div>
)
}
else{
return(
<div>loading...</div>
)
}
}
I think my issue applies to how I originally setup my html with my if/else statement leading to the html constantly showing 'loading...' if I don't have data.results but I'm not too sure on how I'd apply that to my new filtered array
The way I would approach this is by setting your fetched data in state.
Then create another state called something like filteredData as to not mutate your fetched data. Once you filter the data, you want a way to go back to the original data to filter it differently.
On selection of a gender, filter through your fetched data and set filteredData as an array of people objects with your selected gender.
If filteredData exists (which gets set by a useEffect when gender is changed), map over that to display your data. If there is no gender selected (and therefore, no filteredData, map over data.results array.
Check out this jsfiddle
The issue is that when you initially call setData you're passing the full response, but when you call it in FilterData you are passing in a single element array. And then it doesn't re-render because you are testing for data.results which no longer exists.
Try this...
const [data, setData] = useState(null);
const [gender, setGender] = useState('');
useEffect(() => {
fetch(`https://randomuser.me/api/?results=10`)
.then(response => response.json())
.then((data) => {
setData(data.results)
});
}, [])
const FilterData = () => {
if (gender) {
var searchedResult
searchedResult = data.filter(
(e) => e.gender === gender
);
console.log(searchedResult)
console.log(gender)
setData(searchedResult)
}
}
if (data) {
return (
<div>
<div>
<select name="Gender" onChange={(e) => setGender(e.target.value)}>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<button onClick={FilterData}></button>
</div>
<ul>
{data.map((results, idx) => (
<li key={idx}>
<p>{results.name.first} {results.name.last}</p>
</li>
))}
</ul>
</div>
)
} else {
return (
<div>loading...</div>
)
}

Categories