Kid
Kid

Reputation: 2205

How does this arrow function work in my special case passing it through Redux

I learn JavaScript and React Redux and have this question:.

Let's say I have this Redux dispatch:

dispatch(setLogMessage( () =>{"Connecting to env1", 12340, "connecting"})); 

and the reducer is here for the above setLogMessage is this:

   const initialState = {
     log: "",
   };

    case booksActionTypes.LOG_MESSAGE: {
      return {
        ...state,
        log: action.payload,
      };
    }

And in the mapStateToProps it looks like this:

  const [theLog, addLog] = useState([]);

      useEffect(() => {
        if (props.log !== "") {
          addLog([...theLog, createData(props.log)]);
        }
      }, [props.log]);
    
      function createData(message, timestamp, type) {
        console.log('s');
        return { message, timestamp, type };
      }

The problem is I play around and wanted to learn the arrow functions in this context and wanted to have the above props.log, to be a function to resolve the above () =>{"Connecting to env1", 12340, "connecting"}) and pass it to function createData(... Hope you understand my question!

Upvotes: 2

Views: 227

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14385

Immediately returning objects from arrow functions can be syntactically confusing...

The { appears to be opening a new object, but in reality it is opening up a function body.

To resolve this, wrap the object in parenthesis (notice the object property names as well):

() => ({ message: "Connecting to env1", timestamp: 12340, type: "connecting"})

The second problem is that you are never calling this function.

props.log holds that function reference, so to get its values as parameters to createData you need to call it (and pass the individual values).

const values = props.log();
createData(values.message, values.timestamp, values.type);

Summary

  1. Implicit returns require wrapping parenthesis when returning an object.
  2. Objects must contain a property name, not just a value (that's what arrays are for)
  3. Functions must be called, not just passed as props.

Upvotes: 5

Related Questions