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

Warning: Can't perform a React state update on an unmounted component React Native

$
0
0

I don't know why I'm facing this issue. If anyone knows how to deal with it so please help. Thanks in advance

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method,
    in ToastContainer (at connectStyle.js:392)
    in Styled(ToastContainer) (at Root.js:16)
    in RCTView (at View.js:45)
    in View (at Root.js:14)
    in Root (at connectStyle.js:392)
    in Styled(Root) (at LoginScreen.js:93)
    in LoginScreen (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:889)
    in RCTView (at View.js:45)
    in View (at StackViewLayout.tsx:888)
    in RCTView (at View.js:45)
    in View (at StackViewLayout.tsx:887)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewCard.tsx:106)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at screens.native.js:71)
    in Screen (at StackViewCard.tsx:93)
    in Card (at createPointerEventsContainer.tsx:95)
    in Container (at StackViewLayout.tsx:975)
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
- ... 12 more stack frames from framework internals

Rendering random array element from state (React Native)

$
0
0

I'm trying to render a random array item from state so that (e.g - [0] might change to [2] on reload.]

Here is what I tried so far, any tips or ideas please?

here is my state:

     state = {
      randomItem: ['one', 'two', 'three', 'four'],
    },
    selected: null,
    clicked: false,
  };

here is my handleClick function which will randomise the items grabbed from array

  handleClick = () => {
    this.setState({
      clicked: true,
      selected: this.state.randomItem.selected[
        Math.floor(Math.random() * this.state.selected.length)
      ],
    });
  };

here is how im trying to return it

<View>
            <TouchableOpacity onPress={this.handleClick}>
              <Text>{this.state.clicked && this.state.selected}</Text>
            </TouchableOpacity>
          </View>

YouTube API get video url is missing url_encoded_fmt_stream_map and undefined

$
0
0

Restful Info

url: https://www.youtube.com/get_video_info?video_id=${videoId}&el=embedded&ps=default&eurl=&gl=US&hl=en
method: 'GET',
headers: { 'Content-Type': 'text/plain' }

Replaced: ${videoId} = ABEVNHqmbJ4 or YzXi5HpgYGc

I didn't found any stream data on key url_encoded_fmt_stream_map

Use yield inside of setTimeOut in redux saga

$
0
0

In my react project I have the following code.

export function* onDisplayAlert({ payload }: any) {
  payload.id = getUniqueID();
  yield put(setAlert(payload));

  yield setTimeout(() => {
    yield put(removeAlert(payload.id));
  }, 3000);
}

What I want to do here is use yield inside setTimeOut callback.

yield put(removeAlert(payload.id));

But the way I have written this doesn't work.Because arrow function callback is not a generator function, so I can't use yield inside it. How can I use yield inside setTimeOut?

React + TS: How to call a method from outside of a React Functional Component

$
0
0

Im wondering how I can call a method from outside of a React Functional Component. I wrote the function GetUsedLockers() which gets all the used lockers and returns amount. Now I want to call this function from another another component (OrgLocker.tsx) and display the data from the getUsedLockers() function there.

OrgLockerTables.tsx

const OrgLockerTables: React.FC = () => {


    const lockerCall = 'lockers';
    const [lockerData, setLockerData] = useState({
        id: 0,
        guid: "",
        is_currently_claimable: false
    }[""]);

    useEffect(() => {
        componentConsole().then((res) => {
            setLockerData(res);
        })
        // eslint-disable-next-line   
    }, []);
    if (!lockerData) return (<div>Loading...</div>);


    //function to get all used lockers
    function getUsedLockers() {
        let amount = 0;

        for (let i = 0; i < lockerData.length; i++) {
            if (!lockerData.is_currently_claimable) {
                amount++;
            }
        }
        console.log('log from getusedlockers, amount: ', amount)
        return (amount)
    }


    // function to get JSON data from the API
    function componentConsole(): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            http.getRequest('/' + lockerCall).then((res) => {
                let data = res.data.data;

                console.log('data:', data);
                resolve(res.data.data);
            }).catch((error) => {
                console.log(error);
                reject();
            });
        })
    }
}

OrgLocker.tsx

import OrgLockerTables from '../tables/orgLockerTables';

const OrgLockers: React.FC = () => {

    let lockerTable = new OrgLockerTables();

    return (
        <div className="main-div-org">
        <p>Used</p>
        <p>{lockerTable.getUsedLockers()}</p>
        </div>
    );
}

export default OrgLockers;

When trying to make a call to OrgLockerTables and storing it in the lockerTable let it gives the following error:

Expected 1-2 arguments, but got 0.ts(2554)

Any help would be greatly appreciated!

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory

$
0
0

I'm trying to run my test suite but I am getting the following error:

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "/Users/dan/Sites/X"

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at File.initOptions (node_modules/ts-jest/dist/util/hacks.js:23:43)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Here's my jest config in package.json:

"jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
      "\\.(ts|ts)x?$": "ts-jest"
    },
    "testRegex": "/src/.*.spec.(js|ts|tsx)?$",
    "globals": {
      "ts-jest": {
        "useBabelrc": true
      }
    }
  }

If needed, here's the contents of babelrc

{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [
    [
      "module-resolver",
      {
        "alias": {
          "~": "./src"
        }
      }
    ]
  ]
}

Unable to run my Expo app on LAN React Native

$
0
0

I've updated my expo version to the latest. but unfortunately I don't know why my LAN is not working and expo. I've already tried lots of things example.

  1. expo r -c
  2. Delete node_modules and then npm install

but nothing works for me.

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "expo": "^35.0.0",
    "expo-device": "~1.0.0",
    "expo-font": "~7.0.0",
    "native-base": "^2.13.8",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-dialog": "^5.6.0",
    "react-native-gesture-handler": "~1.3.0",
    "react-native-material-menu": "^1.0.0",
    "react-native-modal": "^11.5.3",
    "react-native-modal-filter-picker": "^1.3.4",
    "react-native-multiple-select": "^0.5.5",
    "react-native-paper": "^3.2.1",
    "react-native-reanimated": "~1.2.0",
    "react-native-simple-radio-button": "^2.7.4",
    "react-native-web": "^0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-drawer": "^2.3.3",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "babel-preset-expo": "^7.1.0"
  },
  "private": true
}

React Native Datetime Android Picker Toggle Issue

$
0
0

I'm having an issue with the Android Picker from the React Native Datetime Picker library. This is also my first time using Typescript, but I can't figure out why my Android Picker requires me to press "ok" twice". It also takes two presses of "cancel" to actually cancel out and close the modal. Here's a gif of what issue looks like.

To keep track of the modal, I'm using a React Hook with the state as androidModalVisible. This is also my first time using functional components and React Hooks, so I'm not sure if there is some lifecycle issue I'm not noticing from the androidModalVisible React Hook?

DatePicker.tsx

The Line {androidModalVisible === false ? renderAndroidPicker(): null} is where I render and don't render the modal with androidModalVisible

// Imports: Dependencies
import React, { useState, useEffect } from 'react';
import { Dimensions, Platform, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import RNDateTimePicker from '@react-native-community/datetimepicker';
import Modal from 'react-native-modal';
import moment from 'moment';

// Screen Dimensions
const { height, width } = Dimensions.get('window');

// TypeScript: Types
interface Props {
  title: string;
  mode: 'calendar' | 'spinner' | 'default';
  onChange: (date: Date) => any;
}

// Component: Date Picker
const DatePicker = (props: Props) => {
  // React Hooks: State
  const [ modalVisible, toggle ] = useState(false);
  const [ androidModalVisible, toggleAndroid ] = useState(false);
  const [ date, setDate ] = useState(new Date());

  // Toggle Modal
  const toggleModal = () => {
    try {
      // Check Platform (Android)
      if (Platform.OS === 'android') {
        // React Hook: Toggle Android
        toggleAndroid((androidModalVisible: boolean) => !androidModalVisible);
      }

      // Check Platform (iOS)
      if (Platform.OS === 'ios') {
        // React Hook: Toggle Modal
        toggle((modalVisible: boolean) => !modalVisible);
      }
    }
    catch (error) {
      console.log(error);
    }
  };

  // Select Date
  const selectDate = (event: any, date: Date) => {
    try {
      // Check Platform: Android
      if (Platform.OS === 'android') {
        // Event Type: Set Date
        if (event.type === 'set') {
          // React Hook: Set From Date
          setDate(date);

          // React Hook: Toggle Android
          toggleAndroid(false);

          // React Props: onChange
          props.onChange(date);
        }

        // Event Type: Dismissed
        if (event.type === 'dismissed') {
          // React Hook: Toggle Android
          toggleAndroid(false);
        }
      }

      // Check Platform: Android
      if (Platform.OS === 'ios') {
        setDate(date);

        // React Props: onChange
        props.onChange(date);
      }
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render iOS Picker
  const renderIOSPicker = () => {
    try {
      return (
        <RNDateTimePicker
          mode="date"
          value={date}
          onChange={(event: any, date: Date) => selectDate(event, date)}
        />
      )
    }
    catch (error) {
      console.log(error);
    }
  };

  // Render Android Picker
  const renderAndroidPicker = () => {
    try {
      if (androidModalVisible === true) {
        return (
          <RNDateTimePicker
            mode="date"
            display={props.mode}
            value={date}
            onChange={(event: any, date: Date) => selectDate(event, date)}
          />
        )
      }
      else {
        // Do Nothing

      }
    }
    catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputTitleContainer}>
      <Text style={styles.inputTitle}>{props.title}</Text>
      </View>

      <TouchableOpacity onPress={() => toggleModal()} style={styles.fieldTextContainer}>
        <Text style={styles.fieldText} numberOfLines={1}>{date ? moment(date).format('MMM Do, YYYY') : 'Select'}</Text>

      </TouchableOpacity>

      <View>
        {androidModalVisible === true ? renderAndroidPicker(): null}
      </View>

      <Modal isVisible={modalVisible} style={styles.modal}>
        <View style={styles.modalContainer}>
          <View style={styles.pickerHeaderContainer}>
            <TouchableOpacity onPress={() => toggleModal()} >
              <Text style={styles.doneText}>Done</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.pickerContainer}>
            {renderIOSPicker()}
          </View>
        </View>
      </Modal>
    </View>
  );
}

// Styles
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    width: width - 32,
    marginLeft: 16,
    marginRight: 16,
    justifyContent: 'center',
  },
  modal: {
    margin: 0,
  },
  modalContainer: {
    height: '100%',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  pickerHeaderContainer: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: 40,
    width: width,
    backgroundColor: '#FAFAF8',
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  pickerContainer: {
    height: 220,
    width: width,
    backgroundColor: 'white',
  },
  doneText: {
    fontFamily: 'System',
    color: '#007AFF',
    fontWeight: '600',
    fontSize: 17,
    marginRight: 16,
  },
  stateContainer: {
    alignItems: 'center',
    width: 75,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  inputTitleContainer: {
    width: 75,
    marginBottom: 4,
  },
  inputTitle: {
    color: '#7D7D7D',
    borderColor: '#7D7D7D',
    fontSize: 10,
    fontWeight: '600',
    textTransform: 'uppercase',
  },
  fieldTextContainer: {
    height: 40,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
    borderColor: '#7D7D7D',
    borderBottomWidth: StyleSheet.hairlineWidth,    
  },
  fieldText: {
    width: width - 32 - 20,
    fontFamily: 'System',
    fontSize: 17,
    fontWeight: '400',
    color: '#000000',
    alignSelf: 'center',
  },
  arrowForward: {
    color: 'black',
    opacity: .3,
    marginRight: 7,
  },
});

// Exports
export default DatePicker;

Why can't I use StyleProp on my own component

$
0
0

I'm using TypeScript/Vscode for coding my React Native app. I want code completion on my custom components for style just like React Native's own View component does.

style prop View is defined like this:

style?: StyleProp<ViewStyle>;

When I try it on my own component's props:

type MyViewProps = { style?:StyleProp<ViewStyle> }
class MyView extends Component<MyViewProps>{ ... }

And try to use it the way I use style on a regular view:

<MyView style={{top:-20}}/>

I get the following error:

Type '{ style: { top: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.
  Property 'style' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.ts(2322)

What am I doing wrong?

(Just for clarification: the style does work perfectly on runtime, it's just the code completion/IntelliSense that I can't get to work)

How to declare react navigation argument with typescript?

$
0
0

I want to use typescript with my react hook component.

I use react-navigation for my router.

Create project with npx react-native init MyTSProject --template react-native-template-typescript@6.2.0

version is

"react": "16.8.6",
"react-native": "0.60.5",

Here is what I try

RootScreen.tsx

import React from 'react';

import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity
} from 'react-native';

interface IRootScreen {
  navigation: () => void;
}

const RootScreen: React.FC<IRootScreen> = ({ navigation }) => {
  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={() => navigation.navigate('MainStack')}>
        <Text style={{ fontSize: 40 }}>I am RootScreen</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

export default RootScreen;

I can navigate to MainStack successfully.

But navigation.navigate('MainStack') will shows type () => void no argument navigate on my editor Visual Studio Code.

Is any thing wrong with my interface or I still have to do something with the code ?

Any help would be appreciated.

navigationOptions in react-navigation not work in typescript

$
0
0

I am changing react-native code from javascript to typescript and version upgrade.

but, react-navigationHeaderOptions not working. I can't find the reason.

DocumentNavigation.tsx

import {DocumentsScreen} from '../../screens/Documents/DocumentsScreen'
import DocumentsInFolder from '../../screens/Documents/DocumentsInFolder'

export default createStackNavigator({DocumentsScreen, DocumentsInFolder}, {
  headerMode: 'none', 
  navigationOptions: {
    gesturesEnabled: false,
  },
  transitionConfig : () => ({
    transitionSpec: {
      duration: 0,
      timing: Animated.timing,
      easing: Easing.step0,
    },
}),
})

DocumentsScreen.tsx

export const DocumentsScreen: NavigationScreenComponent<{}> = () =>  {
  return (
    <Container>
      <Text>Hello</Text>
    </Container>
  )
}
DocumentsScreen.navigationOptions = (props: NavigationScreenProps): NavigationStackScreenOptions => {
  return {
    title: "Documents",
    headerStyle: {
      elevation: 0,
      backgroundColor: "darkslategray"
    },
    headerLeft: (
      <HeaderLeft>
        <Buticon style={{width:25, height:25, marginLeft:10}} title={'Account'} image={require('../../../../assets/icons/home/account.png')}
          onPress={()=> props.navigation!.navigate('AccountScreen')}
        />
        <Buticon style={{width:25, height:25, marginLeft:10}} title={'Account'} image={require('../../../../assets/icons/home/tutorfind.png')}
          onPress={()=> props.navigation!.navigate('AccountScreen')}
        /> 
      </HeaderLeft>
    ),
    headerRight: (
      <View style={{flexDirection: 'row', width:100, justifyContent:'flex-end'}}>
        <Buticon style={{width:25, height:25, marginRight:10}} title={'Add'} image={require('../../../../assets/icons/home/add.png')}
        onPress={()=>{    
        })
        }}/>
      </View>
    )
  }
}
const HeaderLeft = styled.View`
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 200;

const Container = styled.View`
  flex: 1;
  justify-content: center;
  align-items: center;
`

I expect just show navigation header. currently, header is entirely invisible. somebody help me plz.

react-native-renimated animation reseting on value set

$
0
0

What am I trying to do?

I am trying to animate a header from my app using react-native-reanimated.

What I did until now?

I've already coded the animation, however the animation reset when I try to animate back to it original value.

Code

import React, { useContext } from 'react';
import Reanimated, { Easing, Extrapolate } from 'react-native-reanimated';
import PacientCategoryButton from '../PacientCategoryButton';
import PacientCategoryIndexContext from './contex';
import { Container } from './styles';

const {
  Value,
  Clock,
  createAnimatedComponent,
  interpolate,
  block,
  cond,
  clockRunning,
  set,
  startClock,
  stopClock,
  useCode,
  timing,
  onChange
} = Reanimated;

const AnimatedContainer = createAnimatedComponent(Container);

export interface PacientCategorySelectorProps {
  setIndex: React.Dispatch<React.SetStateAction<number>>;
}

function runTiming(
  clock: Reanimated.Clock,
  value: Reanimated.Value<number>,
  config: Reanimated.TimingConfig
) {
  const state = {
    finished: new Value(0),
    position: new Value(0),
    time: new Value(0),
    frameTime: new Value(0)
  };

  return block([
    onChange(config.toValue, set(state.frameTime, 0)),
    cond(clockRunning(clock), 0, [
      set(state.finished, 0),
      set(state.time, 0),
      set(state.position, value),
      set(state.frameTime, 0),
      startClock(clock)
    ]),
    timing(clock, state, config),
    cond(state.finished, stopClock(clock)),
    state.position
  ]);
}

const PacientCategorySelector = ({
  setIndex
}: PacientCategorySelectorProps) => {
  const currentIndex = useContext(PacientCategoryIndexContext);
  const animation = new Value<number>(0);
  const translateX = interpolate(animation, {
    inputRange: [0, 1],
    outputRange: [64, -64],
    extrapolate: Extrapolate.EXTEND
  });

  useCode(
    () => [
      set(
        animation,
        runTiming(new Clock(), animation, {
          duration: 270,
          easing: Easing.inOut(Easing.ease),
          toValue: currentIndex
        })
      )
    ],
    [currentIndex]
  );

  return (
    <AnimatedContainer style={{ transform: [{ translateX }] }}>
      <PacientCategoryButton index={0} setIndex={setIndex} label="Hoje" />
      <PacientCategoryButton index={1} setIndex={setIndex} label="Todos" />
    </AnimatedContainer>
  );
};

export default PacientCategorySelector;

Result

https://youtu.be/sT96_lp_WqM

Property 'navigation' does not exists on type 'Readonly& Readonly

$
0
0

I am completely new to react native.

I have the following components:

Playlists:

export default class Playlists extends Component {
  playlists = [
    ...
  ];

  render() {
    const {navigation} = this.props.navigation;

    return (
      <FlatList
        data={this.playlists}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.item}
            onPress={() => navigation.navigate('PlaylistDetails', item)}>
            <Text style={styles.text}>{item.name}</Text>
          </TouchableOpacity>
        )}
      />
    );
  }
}

Details View of a Playlist:

export default class PlaylistDetails extends Component {
  render() {
    const {navigation} = this.props.navigation;
    var songs: Song[] = navigation.getParam('songs');

    return (
      <View>
        <Text>{navigation.getParam('name')}</Text>
        <FlatList
          data={songs}
          renderItem={({item: song}) => <Text>{song.title}</Text>}
        />
      </View>
    );
  }
}

And for navigation:

const screens = {
  Playlists: {
    screen: Playlists,
  },
  PlaylistDetails: {
    screen: PlaylistDetails,
  },
};

const stack = createStackNavigator(screens);

export default createAppContainer(stack);

But at const { navigation } = this.props.navigation; I get an error Property 'navigation' does not exist on type ....

I have tried adding the following code:

interface Props {
    navigation: any
}

and then adding this:

export default class PlaylistDetails extends Component<Props> {
    ...
}

This removes the errors, but when I run the application, I get the following error: TypeError: undefined is not an object (evaluating 'navigation.navigate').

I am totally new to react native and don't know how to solve that. I hope somebody can help me.

How to test expo permissions has been called with camera permissions

$
0
0

Here I have a withPermissions HOC component like below

export function withPermissions<T>(
  WrappedComponent: React.ComponentType<T>,
  requestedPermissions: RequestedPermissions,
) {
  return class WithPermissions extends React.Component<
    WithPermissionsProps & T,
    WithPermissionsState
  > {
    readonly state: WithPermissionsState;
    constructor(props: WithPermissionsProps & T) {
      super(props);
      this.state = {
        focusSubscription: undefined,
        permissions: {},
      };
    }

    readonly checkPermissions = async () => {
      const { permissions } = await Permissions.askAsync(...requestedPermissions);

      const nextPermissions: RecievedPermissions = Object.entries(permissions).reduce(
        (allPermissions, [permissionType, value]) => ({
          ...allPermissions,
          [permissionType]: value.status,
        }),
        {},
      );

      this.setState(state => ({ ...state, permissions: nextPermissions }));
    };

    componentWillMount() {
      this.checkPermissions();
    }

    render() {
      const { permissions } = this.state;

      return <WrappedComponent permissions={permissions} {...(this.props as T)} />;
    }
  };
}

I wrapped my screen with HOC

export const ScanScreen = withPermissions<ScanScreenProps>(component, [
  Permissions.CAMERA,
]);

my test code is looks like

 .mock("expo-permissions", () => ({
    Permissions: {
      askAsync: jest.fn(),
    },
  }));

test("Correct permissions are asked for in scanner screen", async () => {
  const { environment } = renderWithPermissions(ScanScreen);
  await resolveMostRecentOperation<CompleteScanScreenQuery>(environment);
  Permissions.askAsync(Permissions.CAMERA);
});

when i tried with above code i got the below error

TypeError: Permissions.askAsync is not a function

when i change the mocking from expo-permissions to expo like below

.mock("expo", () => ({
    Permissions: {
      askAsync: jest.fn(),
    },
  }));

  const { environment } = renderWithPermissions(ScanScreen);
  await resolveMostRecentOperation<CompleteScanScreenQuery>(environment);
  Permissions.askAsync(Permissions.CAMERA); //undefined

the error will be gone and test is passed but result is undefined

and i tried below code but i am unable to render the BarCodeScanner

test("Correct permissions are asked for in scanner screen", async () => {
  const { environment, getByTestId } = renderWithPermissions(ScanScreen);
  await resolveMostRecentOperation<CompleteScreenQuery>(environment);
  const permissionsSpy = jest.spyOn(Permissions, "askAsync");
  Permissions.askAsync(Permissions.CAMERA);
  expect(permissionsSpy).toHaveBeenCalledWith(Permissions.CAMERA);
  getByTestId("barCodeScanner");
});

error

Unable to find an element with the testID of: barCodeScanner

I am not sure how to do it. Can someone please help me out

"parserOptions.project" has been set for @typescript-eslint/parser

$
0
0

I created a new React Native project with --template typescript

I deleted the template directory which came as part of the boilerplate.

I then proceeded to add ESLint:

module.exports = {
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint"],
  extends: ["airbnb-typescript-prettier"]
};

However, when I open babel.config.js, I get this error

Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser. The file does not match your project config: /Users/Dan/site/babel.config.js. The file must be included in at least one of the projects provided.eslint


How to deal with SQLite migrations in React-Native using TypeORM?

$
0
0

I am writing a React-Native app which heavily relies on local storage, and have chosen TypeORMto handle this.

I am now entering a phase where my project is live, and I want to add new functionalities that require an adjustment to my datamodel. To start, I have used the react-native-example project. I have built my datamodel on this and would now like to implement a migration into it.

There seems to be no definitive manual/guide on how to perform migrations on React-Native. Since I don't have access to the databases of my users, I can't run the migrations manually. So far, I found out that there is a 'migrationsRun' option in the connection settings which can be set to true, forcing migrations to be executed at every launch of the app, if needed.

Question then is: How should the actual migrations be created, what should they look like (plain sql queries?), and where should I put them?

Any guidance on migrations in a react-native app would be very helpful.

Typescript: onPress type

$
0
0

I just ported my react-native project to typescript and have a question about functions as props

im passing:

<DisplayCardsWithLikes
data={testData}
likes={500}
onPress={() => this.props.navigation.navigate("CardDetailScreen")}
/>

to

type Props = {
  onPress: Function
}


const FloatingActionButtonSimple = (props:Props) => {
  const {onPress} = props
  return (
    <View style={styles.containerFab}>
      <TouchableOpacity style={styles.fab} onPress={onPress}>
        <Icon name="plus" size={16} color={"white"} />
      </TouchableOpacity>
    </View>
  );
};

Error:

Error, caused by child onPress:
o overload matches this call.
  Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.
    Type 'Function' is not assignable to type '(event: GestureResponderEvent) => void'.
      Type 'Function' provides no match for the signature '(event: GestureResponderEvent): void'.
  Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.
    Type 'Function' is not assignable to type '(event: GestureResponderEvent) => void'.ts(2769)
index.d.ts(5125, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<...>'
index.d.ts(5125, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<...>'

Summary: onPress passed as prop (is a function). On child type onPress:Function displays an error(the one above), onPress:any works though. I basically don't know which kind of type the onPress prop is

So nothing crazy, but if I define onPress as a function it displays an error, so apparently that's not the correct type. Do you know which type this onPress functions are?

Thanks a lot!

How to fix TypeError: undefined is not an object (evaluating '_config.Svg.G')

$
0
0

I'm getting this error in an expo react native project I'm working on. I've updated all packages to match expo SDK 36, so I'm not sure where the error is coming from.

TypeError: undefined is not an object (evaluating '_config.Svg.G')

How to unlock rotation on one screen in react native

$
0
0

I tried using react-native-orientation in a webview to get it being the only view that would rotate.

import React, {useEffect} from 'react';
import { WebView } from 'react-native-webview';
import Orientation from "react-native-orientation"

export function GameWebViewScreen({navigation}) {
const link = ****

useEffect(() => {
    Orientation.unlockAllOrientations();
}, [])

return <WebView source={{uri: link}}/>
}

I am getting TypeError: null in not an object on unlockAllOrientations call. Does anyone know is this a problem because I haven't configured the native files as it says in instructions here since I don't have the access to them yet or?

I also tried with class component and got the same result.

I am also open for any other suggestions on libraries for controlling rotation on single views.

react navigation: how to pass redux props with NavigationStackScreenComponent type in typescript

$
0
0

I started using typescript in my react native project (typescript newbie) and hit a problem with navigationOptions in functional component with typescript, i solved it thanks to this post here however when i try to pass redux props its telling me

Property 'authType' does not exist on type 'PropsWithChildren<NavigationStackScreenProps<Params, Props>>

this is my code

interface Props {
 authType: string;
}

interface Params {
 routeName: string;
}

const Customer: NavigationStackScreenComponent<Params, Props> = ({
 navigation,
 authType,
 }) => {
 .... Component
 }

 Customer.navigationOptions = ({ navigation }) => ({
   title: navigation.getParam('routeName'),
 });

I think this means that the prop i am passing is not being read although i am passing it.

I used NavigationStackScreenComponent in order to be able to use

Customer.navigationOptions etc

otherwise its gonna tell me

ts] Property 'navigationOptions' does not exist

I am really beggining to love typescript , Any idea how to use authType Props without it screaming at me ?

Viewing all 6207 articles
Browse latest View live