Search code examples
reactjsreduxreact-reduxautosuggest

Rendering and showing selections with autosuggest


i'm using react-autosuggest on a component that fetches a list of options, renders the suggestions and then when the user clicks on one saves it to the store. I'm having trouble when i want to print the chosen value

And then the functions:

On save:

      const onSave = () => {
    props.saveCarColor(value);
    console.log("value", value);
    getSuggestionValue(value);
    if (!props.carColor) {
      return toastError("Error");
    }
    props.history.push(getRoute(""));
  };

Render suggestion:

const renderSuggestion = (item) => {
    return <span>{item.Value}</span>;
  };

get suggestions:

    const getSuggestionValue = (selection) => {
    console.log("selection", selection);
return selection.Value;
  };

inputprops:

    const inputProps = {
    value,
    onChange: (event, { newValue }) => setValue(newValue),
  };

I have this hook declared to update the value:

  const [value, setValue] = useState("");

The thing is, i'm saving it correctly into the store, but onSave after i save it, it should return to the form page and show me the chosen color, just like i'm doing on the getSuggestionValue function with the return, but the text is not showing, i'm not getting any errors either and the console logs that i have print this:

value BLACK
selection BLACK

Solution

  • Finally i ended up using another hook to save the selected color, so now i have this:

    hooks:

    const [value, setValue] = useState("");
      const [selected, setSelected] = useState(null);
    

    inputProps:

    const inputProps = {
        placeholder: "Ej: BLUE",
        value,
        onChange: (event, { newValue }) => setValue(newValue),
      };
    

    renderSuggestions:

    const renderSuggestion = (item) => {
        return <span>{item.Value}</span>;
      };
    

    and getSuggestionValue:

    const getSuggestionValue = (selection) => {
        setSelected(selection.Value);
        return selection.Value;
      };
    

    onSave:

    const onSave = () => {
    if (!selected) {
      return toastError("");
    }
    props.saveCarColor(selected);
    
    
    };
    

    This is how i solved it, i hope it helps!