Add object to array in Redux? - react-native

I'm trying to add a element to a array, which is called allLogbooks. This array contains objects called Logbook. My issue is, how do I fit in code so that it adds the new element to the array which is declared in my reducer? This is my initial state:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
This is my reducer:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
And this is my action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
I then make a POST call to a nodejs server, where it will respond with a message if it was successful, and the logbook which was just created. the following data is what it returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
I then dispatch in the API call, as such:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
I've substituted this by using AsyncStorage to access the array abroad all my views, but I know this is wrong.

I am struggling a little to comprehend your question so I've tried my best. Please let me know if I'm completely off with my answer.
Your reducer:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
Your action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}

Related

i18next not working with languageDetector and i18next-http-backend

i18next not working when passing multiple modules like i18next-http-backend and react-i18next and #os-team/i18next-react-native-language-detector
here is the sample code
i18n
.use(RNLanguageDetector)
.use(initReactI18next)
.use(Backend)
.init(
{
compatibilityJSON: 'v3',
fallbackLng: 'en',
supportedLngs: ['en', 'ar'],
load: 'languageOnly',
// ns: ['translations'],
// defaultNS: 'translations',
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
},
react: {
useSuspense: true,
},
backend: {
crossDomain: false,
withCredentials: false,
overrideMimeType: false,
// loadPath: '${SERVER_APTH}/{{lng}}.json',
request: function (options, url, payload, callback) {
console.log('Request here to get from API');
},
reloadInterval: false,
allowMultiLoading: true,
},
initImmediate: false,
},
(error, t) => {
console.log('loading complete');
console.log('Error', error);
},
);
i18n.languages = ['en', 'ar'];
i18n.on('languageChanged', nextLng => {
console.log('Changed', nextLng);
});
Also tried with custom language detector
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => {
console.log('Tagging here');
cb('en');
},
init: () => {},
cacheUserLanguage: () => {},
};
custom language detector work when i comment backend: { ... } section.
I need to store changed language and get translations according to it.
for changing i'm using
i18n.changeLanguage(nextLocale);
Where nextLocale will be "en" or "ar"

callback are executing multiple times react native

someone please tell me how to fix this issue , this function is calling multiple times , i don't know why and it is so annoying to fix
function NewProduct({ navigation }) {
const supplierApi = useApi(suppliers.getSuppliers);
useEffect(() => {
supplierApi.request();
}, []);
return console.log(supplierApi);
}
the log is like below...
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(0), error: false, loading: true, request: ƒ}
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(7), error: false, loading: false, request: ƒ}
You can call the function as follows, this will same as componentDidMount for class component.
function NewProduct({ navigation }) {
useEffect(() => {
const supplierApi = useApi(suppliers.getSuppliers);
supplierApi.request();
console.log(supplierApi);
}, []);
}

uncaught at generateIDs Error: invalid keyPath

I got a weird error randomly while running my code and here is the code. Please comment if more details are needed.
action.js
export function generateIDs() {
return ({
type: GENERATE_IDS
})
}
reducer.js
const initialState = fromJS({
fields: {
task_completion_date: { ...initialDateState },
sale_id: { ...initialFieldState },
client_id: { ...initialFieldState }
},
progressvalue: 1,
submitting: false,
submitted: false,
valid: false,
statusText: '',
saleID: null,
clientID: null,
reportID: null,
reportDate: datestring,
isLoading: false,
online: true
});

Expo SQLite unable to query DB

I'm currently having a problem trying to query a DB in Expo SQLite.
In my app.js file I get the database from an external source like so:
// load DB for expo
FileSystem.downloadAsync(
'http://example.com/downloads/data.sqlite',
FileSystem.documentDirectory + 'data.sqlite'
)
.then(({ uri }) => {
console.log('Finished downloading to ', uri)
})
.catch(error => {
console.error(error);
});
I can confirm the database is downloaded in console I get:
Finished downloading to file:///var/mobile/Containers/Data/Application/6E1347A8-187E-4EF3-B360-60A0B24E1008/Documents/ExponentExperienceData/%2540anonymous%252Fexpo-sqlite-example-36a92625-6e95-41cc-af6d-a47fc254b237/data.sqlite
this is5507
I then load this in another component:
const db = SQLite.openDatabase('data.sqlite');
Then I run a query like so:
componentDidMount() {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM dr_report_templates',
[],
(success) => console.log(success),
(error) => console.error(error)
);
})
}
I've confirmed that dr_report_templates is in the database.
The error I get is this:
h {
"_complete": false,
"_error": null,
"_running": true,
"_runningTimeout": false,
"_sqlQueue": t {
"first": undefined,
"last": undefined,
"length": 0,
},
"_websqlDatabase": h {
"_currentTask": _ {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
"_db": n {
"_closed": false,
"_name": "data.sqlite",
},
"_running": true,
"_txnQueue": t {
"first": undefined,
"last": undefined,
"length": 0,
},
"version": "1.0",
},
}
In my device I get:
console.error: {"_websqlDatabase": {"version":"1.0","_db":...
Any ideas?
success and error callbacks take two parameters, first is a transaction and second is result/error

Vue.js data changed but view not

I defined an object in data as
export default {
data() {
return {
labelPosition: 'right',
isText: false,
isDate: false,
isExam: false,
isFile: false,
isWrite: false,
stepLists: [],
flowId: '',
txtName: '',
form: {
textName: '',
textPosition: '',
}
the html like this :
when I change the form.textName ,I found it doesn't work
this.$set(this.form, 'textName', temp.name) //not work
this.form={textName:'abc'}
this.form = Object.assign({}, this.form)
//not work
this.$set(this.form,'textName', '---------------------') work well.