Advertisement
Guest User

Untitled

a guest
Jun 12th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import Api from '../api'
  2.  
  3. const FETCH__BEGIN = 'session/LOGIN__BEGIN'
  4. const FETCH__SUCCESS = 'session/LOGIN__SUCCESS'
  5. const FETCH__FAIL = 'session/LOGIN__FAILED'
  6.  
  7. const CLEAR_ERRORS = 'session/CLEAR_ERRORS'
  8.  
  9. export const LOGOUT = 'session/LOGOUT'
  10.  
  11. import { fetchUser } from './user'
  12. import { fetchFavs } from './favs'
  13.  
  14. export const logIn = (username, password) => dispatch => {
  15. dispatch({ type: FETCH__BEGIN })
  16. return fetch(
  17. Api.url + '/users/login', {
  18. method: 'POST',
  19. headers: {
  20. 'Content-Type': 'application/json'
  21. },
  22. body: JSON.stringify({
  23. username: username,
  24. password: password,
  25. })
  26. }
  27. ).then(
  28. response => {
  29. if (response.ok) {
  30. return response.json().then(
  31. data => {
  32. dispatch({
  33. type: FETCH__SUCCESS,
  34. data
  35. })
  36. dispatch(fetchUser(data.id, data.userId))
  37. dispatch(fetchFavs(data.id, data.userId))
  38. }
  39. ).catch(
  40. error => dispatch({
  41. type: FETCH__FAIL,
  42. error: 'Malformed JSON response'
  43. })
  44. )
  45. }
  46. if (response.status === 401) {
  47. return response.json().then(
  48. error => dispatch({
  49. type: FETCH__FAIL,
  50. error: 'Nieprawidłowy login lub hasło. Spróbuj ponownie.'
  51. }))
  52. }
  53. throw new Error('Błąd połączenia')
  54. }
  55. ).catch(
  56. error => dispatch({
  57. type: FETCH__FAIL,
  58. error: error.message
  59. })
  60. )
  61. }
  62.  
  63. export const clearLoginErrors = () => ({
  64. type: CLEAR_ERRORS
  65. })
  66.  
  67. export const logOut = () => ({
  68. type: LOGOUT
  69. })
  70.  
  71. const initialState = {
  72. data: null,
  73. fetching: false,
  74. error: null
  75. }
  76.  
  77. export default (state = initialState, action = {}) => {
  78. switch (action.type) {
  79. case FETCH__BEGIN:
  80. return {
  81. ...state,
  82. fetching: true,
  83. error: null
  84. }
  85. case FETCH__SUCCESS:
  86. return {
  87. ...state,
  88. data: action.data,
  89. fetching: false
  90. }
  91. case FETCH__FAIL:
  92. return {
  93. ...state,
  94. fetching: false,
  95. error: action.error
  96. }
  97. case CLEAR_ERRORS:
  98. return {
  99. ...state,
  100. error: initialState.data
  101. }
  102. case LOGOUT:
  103. return {
  104. ...state,
  105. data: initialState.data
  106. }
  107. default:
  108. return state
  109. }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement