0
votes

Just getting started with React / Redux. I would like to set a default value of my select, when the data comes from store.

App js. (I'm getting datas from Firebase db and i'm fetching it to my Redux-store.

 componentDidMount() {
  let CurrentEmployees = [];
  const db = firebase.firestore();

  db.collection('employees').get()
      .then((result) => {
         CurrentEmployees = result.docs.map(one => one.data());
          this.props.employeesFetched(CurrentEmployees)
      });}

Then i'm trying to get the data from the store in another component "AddScore.js":

const AddScore = () => {
const employees = useSelector(state => state.employees);  **<-- Get data from the store -->**

const db = firebase.firestore();
const[employee, setEmployee] = useState(employees[0]);  **<-- Set default state, but not working, couse data comes later -->**


const addScoreHandler = (e) => {
    e.preventDefault();

    const newScore = {
 employee: +employee
    };

    console.log(employee);  **<-- Without changing a select value it returns "undefined"-->**
};

return(<div>
    <form>
        <select onChange={event => setEmployee(event.target.value)}>

            {
                employees.map((one, index) => {
                    return (<option value={one.id} key={one.id}>{one.name + ' ' + one.lastname}</option> )
                })
            }
        </select>
        <button onClick={addScoreHandler}>AddScore</button>
    </form>

</div>)

};

I would like to save the situation when the user didn't change the select value. My question is how to pass the data from useSelector to local state: const[employee, setEmployee] = useState(?);

Should i get the employees from the firebase once again in "AddScore Component"? ( By using useEffect)

Is another way to do it professionally?

1

1 Answers

1
votes

Yes you can achieve this using useEffect, You can add employees as useEffect dependency.

const [employee, setEmployee] = useState();
const employees = useSelector(state => state.employees);

React.useEffect(() => {
    setEmployee[employees[0]]
}, [employees])