Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

How can I avoid optional chaining when I use redux toolkit?

$
0
0

I am using redux toolkit. I'm trying to store object data called Targetfarms in redux. I assigned a type called Farmstype to Targetfarms.

However, when I bring Targetfarms with useSelector in the MainPage component and I want to use targetfarm.aircon, if I do not use optional chaining in Targetfarms, this error occurs.

Targetfarms is possibly null,

If I use optional chaining, I can get Targetfarms data normally, but I don't want to use optional chaining as much as possible.

How can I fix my code?

This is my code:

export interface Farmstype {    aircon: aircontype;    children: Farmstype[];    equips: euiptype[];    latitude: number;    longitude: number;    modDate: string;    name: string;    placeId: number;    placeInfo: placeInfotype;    productCode: string;    productCodeInfo: productCodeInfotypes;    productLifeCycles: productLifeCyclestype[];    roadNameAddress: string;    stnIds: number;    type: string;}interface InitialState {    Targetfarms: Farmstype | null;}const initialState: InitialState = {    Targetfarms: null,};const postSlice = createSlice({    name: "post",    initialState,    reducers: {        // targetLoadFarm        targetFarm(state, action: PayloadAction<Farmstype>) {            state.Targetfarms = action.payload;        },    }

MainPage

const MainPage = () => {    const { Targetfarms} = useSelector((state: RootState) => state.post);    console.log("Targetfarms:", Targetfarms?.placeId);    // Targetfarms is possibly null,}

Viewing all articles
Browse latest Browse all 6290

Trending Articles