Code Bug Fix: React Native: How value is past by onChangeText in this TextInput code?

Original Source Link

This code is suppose to be a generic handler function for multiple TextInputs, to be invoked by onChangeText :

  getHandler= key =>{
    return val =>{
      this.setState({[key]: val})
    }
  }

.

<TextInput
          onChangeText={this.getHandler('phone')}
        />

I don’t understand where the val got its value, it is not defined explicitly anywhere, if val is passed by onChangeText and doesn’t have to be explicitly named in the handler’s props then why the following doesn’t work without the arrow notation:

  getHandler = key => {
      this.setState({ [key]: val });
  };

also the code doesn’t work without a return, why?

//this code also doesn't work without return  
getHandler = key => {
      val => {
      this.setState({ [key]: val });
    };
  };

Entire code here

Assume that you have written the TextInput. You got your onChangeText function. You would call it like

// To avoid cases when no handler function is set
if(typeof onChangeText === "function"){ 
   onChangeText(this.value);
}

In your first case you are passing return value of your getHandler function which is this function (Unnamed):

val =>{
      this.setState({[key]: val})
    }

In other cases you are not returning a function. So when the TextInput‘s onChangeText is not a function it simply ignores whatever you passed into it.

  • It’s handling event binding using the higher-order function, it’s one of the basic ways of writing function.
Tagged : /

Code Bug Fix: React native, firebase

Original Source Link

Application in React Native + Firebase – study project.

  • I used the firebase function to distinguish between application modes – child, parent.
    I created a functionality of registering, logging in, redirecting to a right mode.

  • Now I want to assign a family id while creating a parent account, then wait to create a child account associated with parent id. If both accounts are created, child share location, parent receive it.

How to implement this functionality? What are the rules for creating this data flow in React Native? Is Redux used for this? The child must be logged in, have internet access to share locations.

  • In the next stages I want to be able to read the child’s SMS in parent mode, send an SOS signal to a parent in child mode.

  • Are there any add-ons available for React Native state (Redux) like the vue.js bookmark for the browser?

Any advice will be very helpful

Tagged : / /

Code Bug Fix: Getting unexpected error with flow in shared module of monorepo using next js

Original Source Link

I have a simple project with monorepo setup. When i try to use/import a shared module inside web next js project am getting the below error

image

Next.js by default won’t compile / transpile modules inside node_modules / out-side of the main folder, therefore you get exception on flow syntax at runtime.

I’m using next-transpile-modules in order to transpile specific modules.

// next.config.js

const withTM = require('next-transpile-modules')(['shared-ui', 'other-shared-lib']);

modules.exports = withTM({
  ...regular next config
});

Tagged : / / / /

Code Bug Fix: {“error”: {“extra”: -2147483648, “what”: 1}} error while playing .mpd dash files in react -native Android

Original Source Link

I have used react-native-video to play DRM content with .mpd extension. But it is giving me an error
{“error”: {“extra”: -2147483648, “what”: 1}}

My video-player is like :

         onBack={this.goBack}
         videoInfo={toJS(videoDetails)}
         videoUrl={dashUrl}
         source={{
           uri: url,
           drm: {
             type: "widevine",
             licenseServer: [licence_server]",
              headers: {
                customdata: xml,
              },
            },
          }}
        />

There is not any error or urls as it is being played in DRM test site.
The above video player uses RNVideo so there is also not an issue as it plays other normal mp4 files.
What can be the error?
Is it a library issue or what?

This seems to be an error that others have seen also.

The usual advice for React Native video playback on Android at this time is make the app use ExoPlayer rather than the Android default player as it seems to give a better experience.

ExoPlayer is a a Google developed Media player for Android and is the usually the standard for a native (i.e. Java or Kotlin) app needing to play back audio and video, at the time of writing.

It appears there may be an issue with ‘autolinking’ the ExoPlayer library (https://github.com/react-native-community/react-native-video/issues/1894#issuecomment-584832293) – the suggested workaround to force your app to use ExoPlayer rather than the default player is, reproduced here from a solution to the issue above:

module.exports = {
  dependencies: {
    'react-native-video': {
      platforms: {
        android: {
          sourceDir: '../node_modules/react-native-video/android-exoplayer',
       },
      },
    },
  },
};

Place the above in your root directory for your app and name it react-native.config.js

There are also reports that characters in the filename in the url may cause the error code you are seeing – see the note here about removing underscores (in fact worth looking at the full tread of this issue): https://github.com/react-native-community/react-native-video/issues/1186#issuecomment-552738393

Tagged : / / / /

Code Bug Fix: Working on react search but getting error TypeError: Cannot read property ‘filter’ of undefined

Original Source Link

i am working on react search but getting error TypeError: Cannot read property ‘filter’ of undefined. i am using react with custom API. i am using input field for autocomplete after type. i am also using react material-ui framework.

Below Code getting error TypeError: Cannot read property ‘filter’ of undefined.

import React, { Component } from 'react'
import ApiService from "../../service/ApiService";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Typography from '@material-ui/core/Typography';
type AppProps = {}
type AppState = {}
class AddUserComponent extends Component<any,any>{

    constructor(props: any){
        super(props);
        this.state ={
            searchArray:[],

        }
        this.saveUser = this.saveUser.bind(this);
        this.searchScripData = this.searchScripData.bind(this); 
    }
    componentDidMount() {
        this.searchScripData(this.requesDATA2());
     }

     requesDATA2()
     {
         let data1= { "symbolOrName":"TATA"};
         return data1;
     }









    saveUser = (e: any) => {
        e.preventDefault();
        let user = {username: this.state.username, password: this.state.password, firstName: this.state.firstName, lastName: this.state.lastName, age: this.state.age, salary: this.state.salary};
        ApiService.addUser(user)
            .then(res => {
                this.setState({message : 'User added successfully.'});
                this.props.history.push('/users');
            });
    }

    searchScripData(searchScrip: any) {
        ApiService.searchScripDataList(searchScrip)
            .then((res) => {
               this.setState({searchArray: res.data.data} )
            });
    }

    //onChange = (e: any) =>
       // this.setState({ [e.target.name]: e.target.value });





//search scrip data
onChange = (searchScrip: any) => {
    console.log('onChanges');

    const { options } = this.props;
    const userInput = searchScrip.currentTarget.value;

    const searchArray = options.filter(
      (optionName: string) =>
        optionName.toLowerCase().indexOf(userInput.toLowerCase()) > -1
    );

    this.setState({
      activeOption: 0,
      searchArray,
      showOptions: true,
      userInput: searchScrip.currentTarget.value
    });
  };

  onClick = (searchScrip: any) => {
    this.setState({
      activeOption: 0,
      searchArray: [],
      showOptions: false,
      userInput: searchScrip.currentTarget.innerText
    });
  };
  onKeyDown = (searchScrip: any) => {
    const { activeOption, searchArray } = this.state;

    if (searchScrip.keyCode === 13) {
      this.setState({
        activeOption: 0,
        showOptions: false,
        userInput: searchArray[activeOption]
      });
    } else if (searchScrip.keyCode === 38) {
      if (activeOption === 0) {
        return;
      }
      this.setState({ activeOption: activeOption - 1 });
    } else if (searchScrip.keyCode === 40) {
      if (activeOption === searchArray.length - 1) {
        console.log(activeOption);
        return;
      }
      this.setState({ activeOption: activeOption + 1 });
    }
  };

//search scrip data


    render() {

//search scrip data
            const {
              onChange,
              onClick,
              onKeyDown,

              state: { activeOption, searchArray, showOptions, userInput }
            } = this;
            let optionList;
            if (showOptions && userInput) {
              if (searchArray.length) {
                optionList = (
                  <ul className="options">
                    {searchArray.map((optionName: any, index: any) => {
                      let className;
                      if (index === activeOption) {
                        className = 'option-active';
                      }
                      return (
                        <li className={className} key={optionName} onClick={onClick}>
                          {optionName}
                        </li>
                      );
                    })}
                  </ul>
                );
              } else {
                optionList = (
                  <div className="no-options">
                    <em>No Option!</em>
                  </div>
                );
              }
            }

//search scrip data

        return(
            <div>
{this.state.searchArray.map((row: any, key: any) => (
                            <TableRow>
                                <TableCell align="left">{row.symbol} asdasdsa</TableCell>
                                <TextField id="filled-search"  label="Search field" type="search" variant="filled" />
                                </TableRow>
                        ))}
        <div className="search">
          <input
            type="text"
            className="search-box"
            onChange={onChange}
            onKeyDown={onKeyDown}
            value={userInput}
          />
          <input type="submit" value="" className="search-btn" />

        {optionList}
        </div>
                <Typography variant="h4" style={style}>Add User</Typography>

    </div>
        );
    }
}
const formContainer = {
    display: 'flex',
    flexFlow: 'row wrap'
};

const style ={
    display: 'flex',
    justifyContent: 'center'

}

export default AddUserComponent;

Ensure props are passed correctly from parent component. And for null safety keep using options?.filter instead of options.filter

Tagged : / /

Code Bug Fix: React Native – TypeError: undefined is not an object [closed]

Original Source Link

React Native version 0.62. I am a bit noob in React Native and I am trying to set up react-native-localize as per this guide https://heartbeat.fritz.ai/how-to-use-react-native-localize-in-react-native-apps-3bb3d510f801 but when I change language and come back to my app I am struggling with this error:

enter image description here

Below you can see my App.js

import React, { Component } from 'react';
import { StatusBar, Text } from 'react-native';
import * as RNLocalize from 'react-native-localize'
import {Router, Scene, Tabs} from 'react-native-router-flux';
import Search from '@screens/Search';
import MyAppointments from '@screens/MyAppointments';
import MyAccount from '@screens/MyAccount';
import CustomTabBar from '@components/CustomTabBar';
import theme from '@styles/theme';
import memoize from 'lodash.memoize';
import i18n from 'i18n-js';

const translationGetters = {
  en: () => require('./translations/en.json'),
  it: () => require('./translations/it.json')
};

const translate = memoize(
  (key, config) => i18n.t(key, config),
  (key, config) => (config ? key + JSON.stringify(config) : key)
);

const setI18nConfig = () => {
  const fallback = { languageTag: 'en' };
  const { languageTag } =
  RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
  fallback;

  translate.cache.clear();

  i18n.translations = { [languageTag]: translationGetters[languageTag]() };
  i18n.locale = languageTag;
};

export default class App extends Component {
  constructor(props) {
    super(props);
    setI18nConfig()
  }

  componentDidMount() {
    RNLocalize.addEventListener('change', this.handleLocalizationChange)
  }

  componentWillUnmount() {
    RNLocalize.removeEventListener('change', this.handleLocalizationChange)
  }

  handleLocalizationChange = () => {
    setI18nConfig()
      .then(() => this.forceUpdate())
      .catch(error => {
        console.error(error)
      })
  };

  render() {
    return (
      ... render code not important for the issue
    );
  }
}

Many thanks to who will help me.

seti18nConfig function doesn’t return a promise for you to use a .then on it. It is a synchronous function. You can simply write

handleLocalizationChange = () => {
    setI18nConfig()
    this.forceUpdate()
};

Tagged : / / /

Code Bug Fix: My project encounters an error while running. Can anyone solve this problem?

Original Source Link

  state = { HomePage: [] };

componentDidMount() {
  axios.get('http://xxxxxx')
  .then(response => {
    this.setState( {HomePage: response.data})
  })
}
   renderImage() {
     return (
        this.state.HomePage.map(Music => <Text>{Music.Name}</Text>)
      )
    }

I called state in this section but when the run project get error

              <View style={{flex:1}}>
                {this.renderImage()}
              </View>

TypeError: undefined is not an object (evaluating ‘this.state.HomePage.map’)

Tagged : / /

Code Bug Fix: How to write actions correctly with Redux-thunk?

Original Source Link

Problem:

I have created a react native application in there I have created the store using redux-thunk middleware. Now I am going to say How I have organized my code. in the actions folder, I have created an action file. This is the code of it.

import * as API from './httpClient';
import * as endPoints from './endpoints';

export const SEND_OTP = 'otp/SEND_OTP';
export const SEND_OTP_SUCCESS = 'otp/SEND_OTP_SUCCESS';
export const SEND_OTP_FAILD = 'otp/SEND_OTP_FAILD';

const sendOtpActionCreator = (value) => {
  return (dispatch) => {
    return API.Post(endPoints.SEND_OTP, {data: value})
      .then((data) => {
        dispatch(SEND_OTP_SUCCESS, data);
      })
      .catch((err) => {
        dispatch(SEND_OTP_FAILD, err);
      });
  };
};

export default {
  sendOtpActionCreator: sendOtpActionCreator,
};

HTTP client and endpoints file looks like this.

import I18n from 'react-native-i18n';
const REST_API = 'myapi';
const getCulture = () => {
  let locale;
  locale = I18n.locale;
  if (locale === 'en') {
    return 'en-us';
  } else if (locale === 'si') {
    return 'si-lk';
  } else if (locale === 'ta') {
    return 'ta-lk';
  }
};

export const SEND_OTP = `${REST_API}/${getCulture()}/api/user/send/otp`;

this is how my HTTP client file is.

import axios from 'axios';

axios.defaults.headers.post['Content-Type'] = 'application/json';

var instance = null;

export const setHeader = async () => {
  // const token = await AsyncStorage.getItem('jwt');
  instance = axios.create({
    baseURL: '',
    timeout: 150000,
    headers: {
      //   Authorization: 'Bearer ' + token,
      'Content-Type': 'application/json',
    },
  });
  instance.interceptors.response.use(
    function (response) {
      return response;
    },
    async function (error) {
      if (error.response.status) {
        if (error.response.status === 401) {
          error = 'Unauthorised';
          return error;
        } else {
          return error;
        }
      } else {
        console.log(error);
      }
    },
  );
};

export const Get = (route, data) => {
  function getData() {
    return instance.get(
      route,
      data == null ? {data: {}} : {data: JSON.stringify(data)},
    );
  }
  if (instance) {
    return getData();
  }
  return setHeader().then(getData);
};

export const Post = (route, data) => {
  function postData() {
    return instance.post(route, JSON.stringify(data));
  }
  if (instance) {
    return postData();
  }

  return setHeader().then(postData);
};

Then I have export actions like this in index.js file of actions folder. This is the code of It.

import * as signin from './signin';

export {signin as signinTypes};
export const signinActions = signin.default;

Then I have created the reducer like this.

import {signinTypes as types} from '_store/actions';

const signin = (
  state = {
    success: false,
    hasError: false,
    error: '',
    otp: '',
  },
  action,
) => {
  console.log(action);
  switch (action.type) {
    case types.SEND_OTP:
      return Object.assign({}, ...state, {hasError: false, error: {}});
    case types.SEND_OTP_SUCCESS:
      return Object.assign({}, ...state, {success: true});
    case types.SEND_OTP_FAILD:
      return Object.assign({}, ...state, {error: true});
    default:
      return state;
  }
};

export default sign-in;

Then I have imported it in combined Reducer like this.

import {combineReducers} from 'redux';
import SignInReducer from '_store/reducers/signin';

const reducers = combineReducers({
  signin: SignInReducer,
});

export default reducers;

And I have used action in my component file like this.

import { connect } from "react-redux";
import { signinActions } from "_store/actions";

const _onPress = (values, navigation, sendOTP) => {
  console.log(values.mobileNo);
  sendOTP(values.mobileNo);
  // navigation.navigate('Otp');
};

const Login = (props) => {
  return (
            <View style={styles.formContainer}>
              <Formik
                initialValues={{
                  mobileNo: "",
                  toggle: true,
                }}
                validationSchema={Yup.object({
                  mobileNo: Yup.string().required("Mobile number required"),
                })}
                onSubmit={(values, formikActions) => {
                  _onPress(values, props.navigation, props.sendOTP);
                  setTimeout(() => {
                    formikActions.setSubmitting(false);
                  }, 500);
                }}
              >
                {(formprops) => (
                  <View>
                    <View>
                      <TextInput
                        style={styles.textField}
                        placeholder={strings("login.mobile")}
                        placeholderTextColor="#bbbbbb"
                        value={formprops.values.mobileNo}
                        onChangeText={formprops.handleChange("mobileNo")}
                        onBlur={formprops.handleBlur("mobileNo")}
                        keyboardType="numeric"
                      />
                    </View>
                    {formprops.touched.mobileNo && formprops.errors.mobileNo ? (
                      <View style={styles.errorMessage}>
                        <AppText styles={styles.errorMessageText}>
                          {formprops.errors.mobileNo}
                        </AppText>
                      </View>
                    ) : null}
                    <View style={styles.togglebuttoncontainer}>
                      <View style={styles.toggleTextView}>
                        <AppText styles={styles.toggleText}>
                          {strings("login.keep-login")}
                        </AppText>
                      </View>
                      <View style={styles.toggleView}>
                        <Switch
                          trackColor={{ false: "#dddddd", true: "#c1d6ee" }}
                          thumbColor={{ false: "#ffffff", true: "#007aff" }}
                          ios_backgroundColor="#dddddd"
                          onValueChange={(value) =>
                            formprops.setFieldValue("toggle", value)
                          }
                          value={formprops.values.toggle}
                          style={styles.toggle}
                        />
                      </View>
                    </View>
                    <SubmitButton
                      onpress={formprops.handleSubmit}
                      btext={strings("login.button-text")}
                    />
                  </View>
                )}
              </Formik>
            </View>
  );
};

const mapStateToProps = (state) => {
  console.log(state);
  return {
    success: state.signin.success,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    sendOTP: (number) => dispatch(signinActions.sendOtpActionCreator(number)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Login);

But when I try to submit the form and do the action it is giving me this error warning.

Possible Unhandled Promise Rejection (id: 0): Error: Actions must be
plain objects. Use custom middleware for async actions.

Can someone help me to correct these files to get rid of this warning? I am very new to Redux-thunk middleware. I tried a lot to find out a solution to this problem but I unable. Thank you

@Atyos. I added comment you can have a look.

could you change the code in your action file:

import * as API from './httpClient';
import * as endPoints from './endpoints';

export const SEND_OTP = 'otp/SEND_OTP';
export const SEND_OTP_SUCCESS = 'otp/SEND_OTP_SUCCESS';
export const SEND_OTP_FAILD = 'otp/SEND_OTP_FAILD';

const sendOtpActionCreator = (value) => {
  return (dispatch) => {
    return API.Post(endPoints.SEND_OTP, {data: value})
      .then((data) => {
        // it is not correct way to call the dispatch
        dispatch(SEND_OTP_SUCCESS, data);

        // the dispatch action accept only the plain object
        // you should try this code
        dispatch({type: SEND_OTP_SUCCESS, payload: data});
      })
      .catch((err) => {
        dispatch(SEND_OTP_FAILD, err);
      });
  };
};

export default {
  sendOtpActionCreator: sendOtpActionCreator,
};

Tagged : / /

Code Bug Fix: how to detect memory leak with debug memory graph in xcode?

Original Source Link

enter image description here

for now, I’m implementing showing tons of images using section list because I have two different section. since there are a lot of images, it’s too slow so I decided to test if there’s memory leak somewhere using debug memory graph. but I’m having tons of memory leakage as you can see on photo.

FYI, I’m a react native developer. I want to find what causes memory leak.

Tagged : /

Code Bug Fix: Getting Child Component Prop from the Parent Component

Original Source Link

I’m using following React Native module:
https://github.com/shariqahmed1/react-native-animated-tree-view

I like to get clicked item from a TreeView.

Documentation says I should be able to get clicked item by onClick prop.
enter image description here

My attempt was like that:

<TreeView
 onPress={() => console.log(props.onClick)} //Cannot get clicked item
 data={data} //Works Okay
/>

I’m able to give source data successfully but I can not get the clicked item from tree view.

How can I get the child component value from parent component?

You should use onClick inplace of onPress as per the doc to get clicked item:

onClick={props.onClick} // <-- will call parent component's onClick

// OR

onClick={(item) => props.onClick(item)}  // <-- will call parent component's onClick

To check console, try below code :

onClick={(item) => { console.log(item); }}

You can use Ref/createRef to give it a unique reference (just like ID) and then you have the access to it:

 class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

In the onclick event handler, use this.onClick() instead of props.onClick() and in this.onClick, you can access child component using this.textInput.current to access the child component.

Tagged : /