How to implement search from backend and use it in fontend?

411 Views Asked by At

I want to implement search from my backend and use it in the frontend TextInput. the problem is that I am getting a blank page, I do not really know what is wrong and I try also to read the error in the console but don't know how to fix it. I want to make a fonctionalty that everytime I call the "text" that is my dependency the state changes and it will fetch new data with the new query. That way it will automatically fetch everytime the user types new data in the inputText. Here below are my codes:

console output

userSerarch.js

const express = require("express");
const router = express.Router();
const pool = require("../database");

router.get("/", (req, res) => {
  const text = req.query.text;
  let mysql = `SELECT * FROM users WHERE name='q'`;
  let query = pool.query(mysql, (err, results) => {
    if (err) throw err;
    res.send(JSON.stringify({ status: 200, error: null, response: results }));
  });
});

module.exports = router;

SearchComponent.js

function SearchComponent() {
  const [users, setUsers] = useState([]);
  const [text, setText] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios
      .get(`http://localhost:3000/api/users?q=${text}`)
      .then((res) => {
        const users = res.data;
        setUsers(users);
        setIsLoading(false);
      })
      .catch((err) => {
        setError(err);
      });
  }, [text]);

  const searchText = (text) => {
    setText(text);
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.textInput}
          onChangeText={(text) => searchText(text)}
          value={text}
          underlineColorAndroid="transparent"
          placeholder="Search"
        />
      </View>
      {isLoading ? (
        <Text>Loading.....</Text>
      ) : error ? (
        <Text>Something went wrong.....</Text>
      ) : (
        <FlatList
          data={users}
          keyExtractor={(item) => item.id.toString()}
          ItemSeparatorComponent={() => Separator()}
          renderItem={({ item }) => (
            <View style={styles.productItemContainer}>
              <View style={styles.productItemMetaContainer}>
                <Text>{item.id}</Text>
                <Text>{item.name}</Text>
                <Text> {item.age}</Text>
                <Text> {item.gender}</Text>
                <Text> {item.country}</Text>
              </View>
            </View>
          )}
        />
      )}
    </View>
  );
}

export default SearchComponent
0

There are 0 best solutions below