'How to get an item from redux store with redux saga
So I have fetched the data from an API and stored it into my Redux store. It's an array of objects, containing 100ish objects. On the front end I am displaying 4 keys from every object.
What I am trying to do now is on the front end, search by a key (name or year) and render the results. Ideally, it would be something like ILIKE
in PSQL, but even having the result only when e.target.value === obj.super.nested.key || obj.super.nested.key_two would
be amazing.
I have tried using the select()
from redux-saga/effects
to no avail.
What I tried originally is on onChange
of the input field, to dispatch an action to a watcher with the e.target.value
as a parameter, which would call a function using that the value as a parameter for select()
.
The code with PSQL instead of redux saga would be :
const [val, setVal] = useState("");
---------------------------------------------
useEffect(() => {
if (val.length >= 3) {
axios.get(`/searchCards/${val}.json`).then(results => {});
} else if (val.length <= 3) {
setCard("");
}
}, [val]);
---------------------------------------------
function handleChange(e) {
e.preventDefault();
setVal(e.target.value);
}
----------------------------------------------
<form noValidate onSubmit={e => this.submit(e)}>
<input
noValidate
name="searchValue"
placeholder="name"
onChange={e => handleChange(e)}
/>
<br />
<br />
<input onChange={e => handleChange(e)} type="date" />
</form>
node.js
app.get("/searchCards/:str.json", (req, res) => {
db.findCard(req.params.str)
.then(results => {
let result = results.rows[0].name;
res.json({ result });
})
.catch(err => {
console.log("error in searching for cards by name: ", err.message);
res.json(null);
});
});
exports.findCard = function findCard(str) {
return db.query(`SELECT * FROM cards WHERE name ILIKE $1 LIMIT 1`, [
str + "%"
]);
};
How could I achieve the same with redux-saga
, searching the store by value, and returning the whole object which contains that value?
Solution 1:[1]
I have found my workaround if anyone wants to know. The documentation on redux-saga
is not very rich, so I did it the only way I knew how.
Basically, when the component mounts, I request the data from the api and store in the redux store. As soon as it's in the store, I render it on the FE.
Since on the change of an input field I want to display only some parts of the previously displayed data, I made a ternary which says if the input field value exists/changes, map through the store and return where input value.toLowerCase().startsWithstartsWith(value_in_the_store)
, else, return all the data.
It works like a charm.
If anyone has another idea, I'd love to hear.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Michael Sivolobov |