ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Wednesday, December 14, 2022

[FIXED] How to set type for () => dispatch(action) in typescript?

 December 14, 2022     react-native, redux-toolkit, typescript   

Issue

I am new to typescript and converting my jsx to tsx files. How can I define the type for a redux dispatch for my onPress prop? I tried using "Function" and the "AppDispatch". Thanks in advance

import { AppDispatch } from "../redux/store"


interface ItemProps {
    item: Custom_date, 
    onPress: AppDispatch, //What should I put here?
    backgroundColor: any,
    textColor: any
}

const Item = ({ item, onPress, backgroundColor, textColor }: ItemProps) => (
    <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
        <Text style={[styles.dateTitle, textColor]}>{item.title}</Text>
    </TouchableOpacity>
);

export const DateHeader = () => {
    const { date } = useSelector((store: RootState) => store.nutrition)
    const dispatch = useDispatch()
    const renderItem = ({ item }) => {
        const backgroundColor = item.id === date.id ? "#033F40" : "#BDF0CC";
        const color = item.id === date.id ? '#BDF0CC' : '#033F40';

        return (
            <Item
                item={item}
                onPress={() => dispatch(setDate(item))}
                backgroundColor={{ backgroundColor }}
                textColor={{ color }}
            />
        );
    }

    return (<>
        <FlatList {props} />
    </>)
}

Solution

The only things you need to know to type a function are the argument types and the return type. In order to find the return type of dispatch() you can check the internals of useDispatch(), but as a general rule (with quite a few exceptions) click handlers will not return anything. Any side effects the function produces, such as by updating a variable or calling an API or updating a database, won't be included in the type signature.

You're also not passing in any parameters in onPress as you can tell from the empty brackets where you define the arrow function, which simplifies things a lot.

As a result your type for onPress will most likely be as follows, if the dispatch function you're calling does not return a value:

interface ItemProps {
    item: Custom_date, 
    onPress: () => void,
    backgroundColor: any,
    textColor: any
}


Answered By - Dakeyras
Answer Checked By - - Senaida (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix